﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BusinessRule.Common;
using System.Configuration;
using DatabaseAccess.DBUtility;
using System.Data.OracleClient;
using System.Data;
using BusinessRule.IBusiness;
using BusinessRule.BusinessFactory;
using BusinessRule.DTO;
using System.Threading.Tasks;
using System.Collections.Concurrent;
using System.Collections;

namespace TransferInsiteDataBusiness
{
    public class TransferInsiteDataBusiness
    {
        uLMSCommonIBusiness m_Common = uMESBusinessFactory.instance.GetuLMSCommonObject();
        uLMSWorkReportIBusiness m_Workreport = uMESBusinessFactory.instance.GetuLMSWorkReportObject();
        uLMSContainerShipIBusiness m_ContainerShip = uMESBusinessFactory.instance.GetuLMSContainerShipObject();
        uLMSContainerIBusiness m_Container = uMESBusinessFactory.instance.GetuLMSContainerObject();
        uLMSCommissioningIBusiness m_Commission = uMESBusinessFactory.instance.GetuLMSCommissioning();
        BusinessRule.Business.AutoStartContainerBusiness m_Auto = new BusinessRule.Business.AutoStartContainerBusiness();
        private static object teamDispatchLock = new object();

        #region TransferInSiteData服务代码
        public void RunDataSync()
        {
            try
            {
                string startDate = GetMes_ServiceStartDate();
                if (SaveMes_Service(startDate) == false)
                {
                    return;
                };
                //LogHelp.WriteLog("TransferMESData定时器启动");
                CreateContainerBaseInfo(); //创建批次基本信息
                // UpdateSpecInfo();//更新批次工序信息
                // RevertContainer();//删除流水卡或更新流水卡状态
                // UpdateMes_ServiceEndTime();//更新最新结束时间到时间转结表
            }
            catch (Exception e)
            {
                LogHelp.WriteError("主方法入口", e);
            }
        }

        #region 公共方法 creat:Wangjh
        /// <summary>
        /// 获取上次写入的时间
        /// </summary>
        /// <returns></returns>
        private string GetMes_ServiceStartDate()
        {
            string strSql = @"SELECT T.START_TIME FROM MES_SERVICE_EXEC_LOG T WHERE T.SERVICE_NAME='ContainerName' ";
            DataSet myDt = DatabaseHelper.Query(strSql);
            if (myDt == null || myDt.Tables.Count == 0)
            {
                return null;
            }
            DataTable dt = myDt.Tables[0];
            if (dt == null || dt.Rows.Count == 0)
            {
                return null;
            }
            return dt.Rows[0]["START_TIME"].ToString();
        }
        /// <summary>
        /// 存取时间
        /// </summary>
        /// <param name="startDate"></param>
        /// <returns></returns>
        private Boolean SaveMes_Service(string startDate)
        {

            string strSql = "";
            if (startDate == null)
            {
                strSql = @"  INSERT INTO MES_SERVICE_EXEC_LOG(SERVICE_NAME,START_TIME) VALUES('ContainerName',SYSDATE)";
            }
            else
            {
                strSql = @"  UPDATE MES_SERVICE_EXEC_LOG T SET START_TIME=SYSDATE WHERE T.SERVICE_NAME='ContainerName'";
            }
            int i = DatabaseHelper.ExecuteSql(strSql);
            if (i > 0)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 更新表的结转标记
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private Boolean UpdateTransferOfTable(string tableName, string ID, object IDValue)
        {
            string updateSql = @"UPDATE " + tableName + " T SET ISTRANSFER=1 WHERE T." + ID + "=:ID";
            OracleParameter[] updateParam = new OracleParameter[1];
            updateParam[0] = DatabaseHelper.NewParameter(":ID", IDValue, OracleType.VarChar);
            int i = DatabaseHelper.ExecuteSql(updateSql, updateParam);
            // InsertOracleLog("更新表" + tableName + "结转标记", i, LogHelp.TranferSql(updateSql, updateParam), "");
            if (i > 0)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
        /// <summary>
        /// 删除原始状态为0的流水卡
        /// </summary>
        public void RevertContainer()
        {
            string strSql = @" SELECT C.CONTAINERID,C.STATUS FROM CONTAINER C 
                                LEFT JOIN CONTAINERCURRENTINFO CCI ON CCI.CONTAINERID=C.CONTAINERID
                                WHERE C.STATUS<>CCI.CONTAINERSTATUS AND C.STATUS<>1"; // 
            DataSet statusDt = DatabaseHelper.Query(strSql);

            string delSql = @" DELETE CONTAINERCURRENTINFO CCI WHERE CCI.CONTAINERID = :CONTAINERID";

            string updateSql = @" UPDATE CONTAINERCURRENTINFO CCI SET CCI.CONTAINERSTATUS=:STATUS WHERE CCI.CONTAINERID = :CONTAINERID";


            foreach (DataRow dr in statusDt.Tables[0].Rows)
            {
                OracleParameter[] deleteParam = new OracleParameter[1];
                deleteParam[0] = DatabaseHelper.NewParameter(":CONTAINERID", dr["CONTAINERID"], OracleType.VarChar);
                OracleParameter[] updateParam = new OracleParameter[2];
                updateParam[0] = DatabaseHelper.NewParameter(":CONTAINERID", dr["CONTAINERID"], OracleType.VarChar);
                updateParam[1] = DatabaseHelper.NewParameter(":STATUS", Convert.ToInt64(dr["STATUS"]), OracleType.Number);

                if (Convert.ToInt64(dr["STATUS"]) == 0)
                {
                    int i = DatabaseHelper.ExecuteSql(delSql, deleteParam);
                    if (i <= 0)
                    {
                        return;
                    }
                }
                else
                {
                    int i = DatabaseHelper.ExecuteSql(updateSql, updateParam);
                    if (i <= 0)
                    {
                        return;
                    }
                }

            };
            //add:Wangjh 2017-7-27 增加在制数为0的卡的清除
            // string delSql2 = @" DELETE CONTAINERCURRENTINFO CCI WHERE cci.containerid IN (SELECT cci.containerid FROM CONTAINERCURRENTINFO CCI WHERE cci.qty=0)";
            // DatabaseHelper.ExecuteSql(delSql2);//删除在制数为0的卡

        }
        /// <summary>
        /// 更新结束时间到时间转结表
        /// </summary>
        private void UpdateMes_ServiceEndTime()
        {
            string updateSql = @" UPDATE MES_SERVICE_EXEC_LOG T SET END_TIME=SYSDATE WHERE T.SERVICE_NAME='ContainerName'";
            int i = DatabaseHelper.ExecuteSql(updateSql);
        }
        /// <summary>
        /// 插入日志记录
        /// add:Wangjh 20180530
        /// </summary>
        /// <param name="message"></param>
        /// <param name="i"></param>
        /// <param name="sql"></param>
        /// <param name="containerName"></param>
        private void InsertOracleLog(string name, string message, int i, string sql, string containerName)
        {
            string IsLog = ConfigurationManager.AppSettings["IsOracleLog"].ToString();
            if (IsLog == "是")
                LogHelp.WriteOrcale("TransferInsiteData_" + name + "@^" + message + "i=" + i + "@^" + sql + "@^" + Convert.ToString(Guid.NewGuid()) + "@^" + containerName);
        }
        #endregion

        #region 插入批次基本信息 creat:Wangjh
        /// <summary>
        /// 获取批次信息
        /// </summary>
        /// <returns></returns>
        private DataTable GetContainerBaseInfo()
        {

            string strSql = @" SELECT distinct ut.attributevalue workflowcheckinfo,CDO.CDONAME,C.CONTAINERID,C.CONTAINERNAME,C.QTY,C.CONTAINERTYPE,C.STATUS CONTAINERSTATUS,C.ORIGINALFACTORYID,
                                   C.TOGETHERFLAG,C.ISSELFMFG,PB.PRODUCTNAME,P.PRODUCTREVISION,P.DESCRIPTION PRODUCTDESCRIPTION,P.PRODUCTID,PB.PRODUCTBASEID,
                                   NULL bomid,M.MFGORDERNAME,M.QTY PLANQTY,M.MFGORDERID,OT.ORDERTYPENAME MFGORDERTYPE,c.originalstartdate,
                                   M.PLANNEDSTARTDATE,M.PLANNEDCOMPLETIONDATE,c.plannedstartdate conPlannedstartdate, FA.FACTORYNAME,FA.FACTORYID,WC.WORKCENTERNAME,WC.WORKCENTERID,
                                   BT.PRODUCTFAMILYNAMES FAMILYLISTNAMES,BT.productfamilyids FAMILYLISTIDS,WF.WORKFLOWID,c.splitfromid,DECODE(cdo.cdoname,'MachineMfgWorkFlow',0,-1) isinstore,cci2.techniquedate,cci2.techniqueemployeeid,
                                   p.workflowroute,cci2.materialemployeeid,cci2.materialdate,cci2.sendmaterialworkid,cci2.sendmaterialqty,cci2.sendmaterialdate,ut1.attributevalue Originalfactorycode,c.mfgworkflowid FROM (
                                    select * from container c where c.originalstartdate>=sysdate-3 AND C.STATUS =1 AND nvl2( C.PARENTCONTAINERID,1,0)=0 AND  nvl2( C.TOGETHERFLAG,1,0)=1 AND C.QTY >=1
                                    union all
                                    select c.* from container c 
                                    left join containersplitinfo cps on cps.splitcontainername=c.containername and cps.isuse=0
                                    where cps.checkdata>=sysdate-3 and c.originalstartdate<sysdate-3 AND C.STATUS =1 AND nvl2( C.PARENTCONTAINERID,1,0)=0  AND  nvl2( C.TOGETHERFLAG,1,0)=1 AND C.QTY >=1
                                    ) C
                                   LEFT JOIN CONTAINERCURRENTINFO CCI ON CCI.CONTAINERID=C.CONTAINERID
                                   LEFT JOIN PRODUCT P ON C.PRODUCTID = P.PRODUCTID
                                   INNER JOIN PRODUCTBASE PB ON PB.PRODUCTBASEID = P.PRODUCTBASEID
                                   LEFT JOIN MFGORDER M  ON M.MFGORDERID = C.MFGORDERID 
                                   LEFT JOIN ORDERTYPE OT ON OT.ORDERTYPEID=M.ORDERTYPEID
                                   INNER JOIN CURRENTSTATUS CU  ON CU.CURRENTSTATUSID = C.CURRENTSTATUSID
                                   LEFT JOIN WORKFLOWSTEP WS ON WS.WORKFLOWSTEPID = CU.WORKFLOWSTEPID
                                   LEFT JOIN WORKFLOW WF  ON WF.WORKFLOWID = WS.WORKFLOWID
                                   LEFT JOIN CDODEFINITION CDO ON CDO.CDODEFID = WF.CDOTYPEID
                                   LEFT JOIN WORKCENTER WC  ON WC.WORKCENTERID = C.WORKCENTERID
                                   LEFT JOIN FACTORY FA ON FA.FACTORYID=C.ORIGINALFACTORYID
                                   LEFT JOIN containercurrentinfo cci2 ON cci2.containerid=c.splitfromid--当前为分批卡
                                   left join userattribute ut on ut.parentid=c.containerid and ut.userattributename='工艺校对'
                                   left join userattribute ut1 on ut1.parentid=c.Originalfactoryid and ut1.userattributename='分厂代码'
                                    LEFT JOIN(
                                          SELECT CFL.CONTAINERID,listagg(pf.productfamilyname,' ') WITHIN GROUP (ORDER BY null) PRODUCTFAMILYNAMES,listagg(pf.productfamilyid,',') WITHIN GROUP (ORDER BY null) productfamilyids FROM CONTAINERPRODUCTFAMILYLIST CFL 
                                        LEFT JOIN PRODUCTFAMILY PF ON PF.PRODUCTFAMILYID=CFL.PRODUCTFAMILYLISTID
                                        GROUP BY CFL.CONTAINERID
                                                ) BT ON BT.CONTAINERID=C.CONTAINERID--查出机型
                                   WHERE nvl(CCI.CONTAINERID,'0')='0'";

            //if ( startDate != null) {
            //    strSql += string.Format("  AND C.LASTACTIVITYDATE>TO_DATE('{0}','yyyy-mm-dd hh24:mi:ss') ", startDate);
            //}              
            DataSet myDt = DatabaseHelper.Query(strSql);
            if (myDt == null || myDt.Tables.Count == 0)
            {
                return null;
            }
            return myDt.Tables[0];
        }
        /// <summary>
        /// 插入批次基本信息
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private Boolean InsertContainerBaseInfoOfRow(DataRow dr)
        {
            string inserSql = @" INSERT INTO CONTAINERCURRENTINFO C(CONTAINERID,CONTAINERNAME,QTY,CONTAINERTYPE,CONTAINERSTATUS,
ORIGINALFACTORYID,TOGETHERFLAG,ISSELFMFG,PRODUCTNAME,PRODUCTREVISION,PRODUCTDESCRIPTION,PRODUCTID,
PRODUCTBASEID,BOMID,MFGORDERNAME,PLANQTY,MFGORDERID,MFGORDERTYPE,PLANNEDSTARTDATE,PLANNEDCOMPLETIONDATE,
FACTORYNAME,FACTORYID,WORKCENTERNAME,WORKCENTERID,FromWorkCenterName,FromWorkCenterID,ArrangementNum,
DispatchNum,IsDispatch,DispatchChangeNum,WorkCenterDispatchNum,TeamDispatchNum,FirstCheckNum,
StepCheckNum,SplitNum,ShipNum,IsShip,ISREWORK,ISINSTORE,ALLLOSSQTY,COMMISSIONINGNUM,ISCOMMISSIONING
,FAMILYLISTNAMES,FAMILYLISTIDS,splitfromid,techniquedate,techniqueemployeeid,workflowroute,containerno,materialdate,materialemployeeid,
sendmaterialworkid,sendmaterialqty,sendmaterialdate,RealContainerNo,IsInPool,Expectmaterialdate,OriginalStartDate,
WORKFLOWNAME,WORKFLOWREVISION,WORKFLOWBASEID,WORKFLOWID,WORKFLOWSTEPID,WORKFLOWSTEPNAME,WORKFLOWSTEPSEQUENCE,SPECNAME,SPECREVISION,
SPECDESCRIPTION,SPECID,SPECBASEID,ISKEY,SPECNO,PARENTSPECNO,SPECFACTORYID,actualstepid)
VALUES(:CONTAINERID,:CONTAINERNAME,:QTY,:CONTAINERTYPE,:CONTAINERSTATUS,:ORIGINALFACTORYID,
:TOGETHERFLAG,:ISSELFMFG,:PRODUCTNAME,:PRODUCTREVISION,:PRODUCTDESCRIPTION,:PRODUCTID,:PRODUCTBASEID,
:BOMID,:MFGORDERNAME,:PLANQTY,:MFGORDERID,:MFGORDERTYPE,:PLANNEDSTARTDATE,:PLANNEDCOMPLETIONDATE,
:FACTORYNAME,:FACTORYID,:WORKCENTERNAME,:WORKCENTERID,:FromWorkCenterName,:FromWorkCenterID,0,0,0,
0,0,0,0,0,0,0,0,0,:ISINSTORE,0,0,0,:FAMILYLISTNAMES,:FAMILYLISTIDS,:splitfromid,:techniquedate,:techniqueemployeeid,:workflowroute,:containerno,:materialdate,:materialemployeeid,
:sendmaterialworkid,:sendmaterialqty,:sendmaterialdate,:RealContainerNo,1,:Expectmaterialdate,:OriginalStartDate,
:WORKFLOWNAME,:WORKFLOWREVISION,:WORKFLOWBASEID, :WORKFLOWID,:WORKFLOWSTEPID,:WORKFLOWSTEPNAME,:WORKFLOWSTEPSEQUENCE, :SPECNAME,:SPECREVISION,
:SPECDESCRIPTION,:SPECID,:SPECBASEID,:ISKEY,:SPECNO,:PARENTSPECNO,:SPECFACTORYID,:actualstepid)";

            //bomid字段处理
            var workflowid = dr["mfgworkflowid"].ToString();
            if (dr["ISINSTORE"].ToString() == "0")
            {
                workflowid = dr["WORKFLOWID"].ToString();
            }
            var bomid = DatabaseHelper.GetSingle(string.Format(@"SELECT MAX(b.bomid) bomid FROM bom b WHERE b.workflowid='{0}'", workflowid));

            OracleParameter[] insertParam = new OracleParameter[59];
            insertParam[0] = DatabaseHelper.NewParameter(":CONTAINERID", dr["CONTAINERID"], OracleType.VarChar);
            insertParam[1] = DatabaseHelper.NewParameter(":CONTAINERNAME", dr["CONTAINERNAME"], OracleType.VarChar);
            insertParam[2] = DatabaseHelper.NewParameter(":QTY", dr["QTY"], OracleType.Number);
            insertParam[3] = DatabaseHelper.NewParameter(":CONTAINERTYPE", dr["CONTAINERTYPE"], OracleType.Number);
            insertParam[4] = DatabaseHelper.NewParameter(":CONTAINERSTATUS", dr["CONTAINERSTATUS"], OracleType.Number);
            insertParam[5] = DatabaseHelper.NewParameter(":ORIGINALFACTORYID", dr["ORIGINALFACTORYID"], OracleType.VarChar);
            insertParam[6] = DatabaseHelper.NewParameter(":TOGETHERFLAG", dr["TOGETHERFLAG"], OracleType.VarChar);
            insertParam[7] = DatabaseHelper.NewParameter(":ISSELFMFG", dr["ISSELFMFG"], OracleType.Number);
            insertParam[8] = DatabaseHelper.NewParameter(":PRODUCTNAME", dr["PRODUCTNAME"], OracleType.VarChar);
            insertParam[9] = DatabaseHelper.NewParameter(":PRODUCTREVISION", dr["PRODUCTREVISION"], OracleType.VarChar);
            insertParam[10] = DatabaseHelper.NewParameter(":PRODUCTDESCRIPTION", dr["PRODUCTDESCRIPTION"], OracleType.VarChar);
            insertParam[11] = DatabaseHelper.NewParameter(":PRODUCTID", dr["PRODUCTID"], OracleType.VarChar);
            insertParam[12] = DatabaseHelper.NewParameter(":PRODUCTBASEID", dr["PRODUCTBASEID"], OracleType.VarChar);
            insertParam[13] = DatabaseHelper.NewParameter(":BOMID", bomid == null ? "" : bomid.ToString(), OracleType.VarChar);
            insertParam[14] = DatabaseHelper.NewParameter(":MFGORDERNAME", dr["MFGORDERNAME"], OracleType.VarChar);
            insertParam[15] = DatabaseHelper.NewParameter(":PLANQTY", string.IsNullOrWhiteSpace(dr["PLANQTY"].ToString()) ? dr["QTY"] : dr["PLANQTY"], OracleType.Number);
            insertParam[16] = DatabaseHelper.NewParameter(":MFGORDERID", dr["MFGORDERID"], OracleType.VarChar);
            insertParam[17] = DatabaseHelper.NewParameter(":MFGORDERTYPE", dr["MFGORDERTYPE"], OracleType.VarChar);
            insertParam[18] = DatabaseHelper.NewParameter(":PLANNEDSTARTDATE", dr["PLANNEDSTARTDATE"], OracleType.DateTime);
            insertParam[19] = DatabaseHelper.NewParameter(":PLANNEDCOMPLETIONDATE", dr["PLANNEDCOMPLETIONDATE"], OracleType.DateTime);
            insertParam[20] = DatabaseHelper.NewParameter(":FACTORYNAME", dr["FACTORYNAME"], OracleType.VarChar);
            insertParam[21] = DatabaseHelper.NewParameter(":FACTORYID", dr["FACTORYID"], OracleType.VarChar);
            insertParam[22] = DatabaseHelper.NewParameter(":WORKCENTERNAME", dr["WORKCENTERNAME"], OracleType.VarChar);
            insertParam[23] = DatabaseHelper.NewParameter(":WORKCENTERID", dr["WORKCENTERID"], OracleType.VarChar);
            insertParam[24] = DatabaseHelper.NewParameter(":FromWorkCenterName", dr["WORKCENTERNAME"], OracleType.VarChar);
            insertParam[25] = DatabaseHelper.NewParameter(":FromWorkCenterID", dr["WORKCENTERID"], OracleType.VarChar);
            insertParam[26] = DatabaseHelper.NewParameter(":FAMILYLISTNAMES", dr["FAMILYLISTNAMES"].ToString().Trim(), OracleType.VarChar);
            insertParam[27] = DatabaseHelper.NewParameter(":FAMILYLISTIDS", dr["FAMILYLISTIDS"], OracleType.VarChar);
            insertParam[28] = DatabaseHelper.NewParameter(":splitfromid", dr["splitfromid"], OracleType.VarChar);
            insertParam[29] = DatabaseHelper.NewParameter(":ISINSTORE", dr["ISINSTORE"], OracleType.Number);
            var workflowCheckInfo = dr["workflowcheckinfo"].ToString(); string techniqueEmployeeID = dr["techniqueemployeeid"].ToString();
            var techniqueDate = dr["techniquedate"].ToString();
            if (!string.IsNullOrWhiteSpace(workflowCheckInfo) && string.IsNullOrWhiteSpace(techniqueEmployeeID))
            {
                techniqueEmployeeID = workflowCheckInfo.Split('&')[1];
                techniqueDate = workflowCheckInfo.Split('&')[0];
            }
            if (string.IsNullOrWhiteSpace(techniqueDate))
            {
                insertParam[30] = DatabaseHelper.NewParameter(":TechniqueDate", DBNull.Value, OracleType.DateTime);
            }
            else
            {
                insertParam[30] = DatabaseHelper.NewParameter(":TechniqueDate", DateTime.Parse(techniqueDate), OracleType.DateTime);
            }
            insertParam[31] = DatabaseHelper.NewParameter(":techniqueemployeeid", techniqueEmployeeID, OracleType.VarChar);
            insertParam[32] = DatabaseHelper.NewParameter(":workflowroute", dr["workflowroute"], OracleType.VarChar);
            //批次号containerno
            string containerNo = "";
            if (dr["CONTAINERTYPE"].ToString() == "7")
                containerNo = (dr["TOGETHERFLAG"].ToString()).Replace(dr["PRODUCTNAME"].ToString() + "/", null);
            else
                containerNo = (dr["CONTAINERNAME"].ToString()).Replace(dr["PRODUCTNAME"].ToString() + "/", null);
            insertParam[33] = DatabaseHelper.NewParameter(":containerno", containerNo, OracleType.VarChar);
            //
            insertParam[34] = DatabaseHelper.NewParameter(":materialdate", dr["materialdate"], OracleType.DateTime);
            insertParam[35] = DatabaseHelper.NewParameter(":materialemployeeid", dr["materialemployeeid"], OracleType.VarChar);
            insertParam[36] = DatabaseHelper.NewParameter(":sendmaterialworkid", dr["sendmaterialworkid"], OracleType.VarChar);
            insertParam[37] = DatabaseHelper.NewParameter(":sendmaterialqty", dr["sendmaterialqty"], OracleType.Number);
            insertParam[38] = DatabaseHelper.NewParameter(":sendmaterialdate", dr["sendmaterialdate"], OracleType.DateTime);
            insertParam[39] = DatabaseHelper.NewParameter(":RealContainerNo", dr["CONTAINERNAME"].ToString().Replace(dr["PRODUCTNAME"].ToString() + "/", ""), OracleType.VarChar);
            //if (dr["Originalfactorycode"].ToString() == "602")
            //{
            //    insertParam[40] = DatabaseHelper.NewParameter(":Expectmaterialdate", dr["conPlannedstartdate"], OracleType.DateTime);
            //}
            //else
            insertParam[40] = DatabaseHelper.NewParameter(":Expectmaterialdate", DBNull.Value, OracleType.DateTime);
            insertParam[41] = DatabaseHelper.NewParameter(":OriginalStartDate", dr["OriginalStartDate"], OracleType.DateTime);

            //获取工艺数据
            DataTable dtWf = GetContainerWorkflowInfo(dr["CONTAINERID"].ToString());
            if (dtWf.Rows.Count > 0)
            {
                DataRow drWf = dtWf.Rows[0];
                insertParam[42] = DatabaseHelper.NewParameter(":WORKFLOWNAME", drWf["WORKFLOWNAME"], OracleType.VarChar);
                insertParam[43] = DatabaseHelper.NewParameter(":WORKFLOWREVISION", drWf["WORKFLOWREVISION"], OracleType.VarChar);
                insertParam[44] = DatabaseHelper.NewParameter(":WORKFLOWBASEID", drWf["WORKFLOWBASEID"], OracleType.VarChar);
                insertParam[45] = DatabaseHelper.NewParameter(":WORKFLOWID", drWf["WORKFLOWID"], OracleType.VarChar);
                insertParam[46] = DatabaseHelper.NewParameter(":WORKFLOWSTEPID", drWf["WORKFLOWSTEPID"], OracleType.VarChar);
                insertParam[47] = DatabaseHelper.NewParameter(":WORKFLOWSTEPNAME", drWf["WORKFLOWSTEPNAME"], OracleType.VarChar);
                insertParam[48] = DatabaseHelper.NewParameter(":WORKFLOWSTEPSEQUENCE", drWf["WORKFLOWSTEPSEQUENCE"], OracleType.Number);
                insertParam[49] = DatabaseHelper.NewParameter(":SPECNAME", drWf["SPECNAME"], OracleType.VarChar);
                insertParam[50] = DatabaseHelper.NewParameter(":SPECREVISION", drWf["SPECREVISION"], OracleType.VarChar);
                insertParam[51] = DatabaseHelper.NewParameter(":SPECDESCRIPTION", drWf["SPECDESCRIPTION"], OracleType.VarChar);
                insertParam[52] = DatabaseHelper.NewParameter(":SPECID", drWf["SPECID"], OracleType.VarChar);
                insertParam[53] = DatabaseHelper.NewParameter(":SPECBASEID", drWf["SPECBASEID"], OracleType.VarChar);
                insertParam[54] = DatabaseHelper.NewParameter(":ISKEY", drWf["ISKEY"], OracleType.VarChar);
                insertParam[55] = DatabaseHelper.NewParameter(":SPECNO", drWf["SPECNO"], OracleType.VarChar);
                insertParam[56] = DatabaseHelper.NewParameter(":PARENTSPECNO", drWf["PARENTSPECNO"], OracleType.VarChar);
                insertParam[57] = DatabaseHelper.NewParameter(":SPECFACTORYID", drWf["SPECFACTORYID"], OracleType.VarChar);
                insertParam[58] = DatabaseHelper.NewParameter(":actualstepid", drWf["WORKFLOWSTEPID"], OracleType.VarChar);
            }
            else
            {
                insertParam[42] = DatabaseHelper.NewParameter(":WORKFLOWNAME", null, OracleType.VarChar);
                insertParam[43] = DatabaseHelper.NewParameter(":WORKFLOWREVISION", null, OracleType.VarChar);
                insertParam[44] = DatabaseHelper.NewParameter(":WORKFLOWBASEID", null, OracleType.VarChar);
                insertParam[45] = DatabaseHelper.NewParameter(":WORKFLOWID", null, OracleType.VarChar);
                insertParam[46] = DatabaseHelper.NewParameter(":WORKFLOWSTEPID", null, OracleType.VarChar);
                insertParam[47] = DatabaseHelper.NewParameter(":WORKFLOWSTEPNAME", null, OracleType.VarChar);
                insertParam[48] = DatabaseHelper.NewParameter(":WORKFLOWSTEPSEQUENCE", null, OracleType.Number);
                insertParam[49] = DatabaseHelper.NewParameter(":SPECNAME", null, OracleType.VarChar);
                insertParam[50] = DatabaseHelper.NewParameter(":SPECREVISION", null, OracleType.VarChar);
                insertParam[51] = DatabaseHelper.NewParameter(":SPECDESCRIPTION", null, OracleType.VarChar);
                insertParam[52] = DatabaseHelper.NewParameter(":SPECID", null, OracleType.VarChar);
                insertParam[53] = DatabaseHelper.NewParameter(":SPECBASEID", null, OracleType.VarChar);
                insertParam[54] = DatabaseHelper.NewParameter(":ISKEY", null, OracleType.VarChar);
                insertParam[55] = DatabaseHelper.NewParameter(":SPECNO", null, OracleType.VarChar);
                insertParam[56] = DatabaseHelper.NewParameter(":PARENTSPECNO", null, OracleType.VarChar);
                insertParam[57] = DatabaseHelper.NewParameter(":SPECFACTORYID", null, OracleType.VarChar);
                insertParam[58] = DatabaseHelper.NewParameter(":actualstepid", null, OracleType.VarChar);
            }

            int i = DatabaseHelper.ExecuteSql(inserSql, insertParam);
            InsertOracleLog(System.Reflection.MethodBase.GetCurrentMethod().Name, "插入批次基本信息", i, LogHelp.TranferSql(inserSql, insertParam), dr["CONTAINERNAME"].ToString());
            if (i > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 创建批次基本信息
        /// </summary>
        /// <returns></returns>
        private Boolean CreateContainerBaseInfo()
        {
            DataTable containerData = GetContainerBaseInfo();
            if (containerData == null)
            {
                return false;
            }
            //foreach (DataRow dr in containerData.Rows)
            //{
            //    if (InsertContainerBaseInfoOfRow(dr) == false)
            //    {
            //        return false;
            //    }
            //}
            //Parallel.For(0, containerData.Rows.Count, new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount}, (int i) =>
            //{
            //    InsertContainerBaseInfoOfRow(containerData.Rows[i]);
            //});

            //转化为线程安全对象
            ConcurrentBag<DataRow> cd = new ConcurrentBag<DataRow>();
            foreach (DataRow dr in containerData.Rows)
            {
                cd.Add(dr);
            }
            Parallel.ForEach(cd, new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount }, (item, ParallelLoopState) =>
            {
                InsertContainerBaseInfoOfRow(item);
            });
            return true;
        }

        /// <summary>
        /// 获取批次的工艺信息
        /// </summary>
        /// <param name="containerID"></param>
        /// <returns></returns>
        private DataTable GetContainerWorkflowInfo(string containerID)
        {
            string sql = string.Format(@"SELECT ws.workflowstepid,ws.workflowstepname,WS.SEQUENCE WorkflowStepSequence
                    ,WF.WORKFLOWID,WFB.WORKFLOWNAME,WF.WORKFLOWREVISION,WF.WORKFLOWBASEID
                    ,SB2.SPECNAME,S.SPECREVISION,S.DESCRIPTION AS SpecDescription,S.SPECID,S.SPECBASEID,S.ISKEY,s.lastcheck,S.SPECNO,S.PARENTSPECNO,
                    S.FACTORYID SpecFactoryID
                     FROM CONTAINER C
                    inner JOIN CURRENTSTATUS CU  ON C.CURRENTSTATUSID=CU.CURRENTSTATUSID
                    inner JOIN WORKFLOWSTEP WS ON WS.WORKFLOWSTEPID = CU.WORKFLOWSTEPID
                    LEFT JOIN WORKFLOW WF  ON WF.WORKFLOWID = WS.WORKFLOWID
                    LEFT JOIN WORKFLOWBASE WFB ON WFB.WORKFLOWBASEID = WF.WORKFLOWBASEID
                    LEFT JOIN SPECBASE SB ON SB.SPECBASEID = WS.SPECBASEID 
                    LEFT JOIN SPEC S ON S.SPECID=NVL(SB.REVOFRCDID, WS.SPECID) 
                    LEFT JOIN SPECBASE SB2 ON S.SPECBASEID=SB2.SPECBASEID 
                    WHERE c.containerid = '{0}'", containerID);
            return DatabaseHelper.Query_ReturnDatTable(sql);
        }

        #endregion

        #region 更新工艺信息 creat:Wangjh
        /// <summary>
        /// 获取工艺工序信息
        /// </summary>
        /// <param name="startDate"></param>
        /// <remarks>添加C.CONTAINERTYPE查询 tianFW 2017年12月7日</remarks>
        /// <returns></returns>
        private DataTable GetSpecInfo()
        {
            string strSql = @" SELECT C.QTY,C.STATUS AS CONTAINERSTATUS,WFB.WORKFLOWNAME,WF.WORKFLOWREVISION,WF.WORKFLOWBASEID,C.CONTAINERTYPE,
WF.WORKFLOWID,WS.WORKFLOWSTEPID,cci.workflowid cciworkflowid,CCI.WORKFLOWSTEPID AS CCIWORKFLOWSTEPID,WS.WORKFLOWSTEPNAME,CCI.WORKFLOWSTEPSEQUENCE AS CCIWORKFLOWSTEPSEQUENCE,WS.SEQUENCE WorkflowStepSequence,SB2.SPECNAME,
S.SPECREVISION,S.DESCRIPTION AS SpecDescription,S.SPECID,S.SPECBASEID,S.ISKEY,s.lastcheck,S.SPECNO,S.PARENTSPECNO,
S.FACTORYID SpecFactoryID,C.CONTAINERID,C.CONTAINERNAME,CCI.ISINSTORE,CCI.WORKCENTERDISPATCHID,CCI.Shipnum,cci.shipid,
CCI.Originalfactoryid,fa.factoryname Originalfactoryname,cci.fromworkcenterid,cci.fromworkcentername,CCI.bomid ccibomid,
P.description productdescription,C.splitfromid,CDO.CDONAME,WS.WORKFLOWSTEPID actualstepid,cci.actualstepid cciactualstepid,nvl(s.controlcode,ws.controlcode) controlcode  
FROM CONTAINER C
inner JOIN CURRENTSTATUS CU  ON C.CURRENTSTATUSID=CU.CURRENTSTATUSID
inner JOIN WORKFLOWSTEP WS ON WS.WORKFLOWSTEPID = CU.WORKFLOWSTEPID
INNER JOIN CONTAINERCURRENTINFO CCI ON CCI.CONTAINERID=C.CONTAINERID and decode(cci.actualstepid,cu.workflowstepid,'1','0')='0'
left join factory fa on fa.factoryid=cci.originalfactoryid
LEFT JOIN WORKFLOW WF  ON WF.WORKFLOWID = WS.WORKFLOWID
LEFT JOIN PRODUCT P ON C.PRODUCTID = P.PRODUCTID                                 
LEFT JOIN BOMBASE BB ON BB.BOMBASEID = P.BOMBASEID                                   
LEFT JOIN BOM B ON B.BOMID=NVL(BB.REVOFRCDID,P.BOMID) --AND B.BOMBASEID=BB.BOMBASEID
LEFT JOIN CDODEFINITION CDO ON CDO.CDODEFID = WF.CDOTYPEID
LEFT JOIN WORKFLOWBASE WFB ON WFB.WORKFLOWBASEID = WF.WORKFLOWBASEID
LEFT JOIN SPECBASE SB ON SB.SPECBASEID = WS.SPECBASEID 
LEFT JOIN SPEC S ON S.SPECID=NVL(SB.REVOFRCDID, WS.SPECID) 
LEFT JOIN SPECBASE SB2 ON S.SPECBASEID=SB2.SPECBASEID ";
            //strSql += string.Format("  WHERE WS.WORKFLOWSTEPID IS NOT NULL AND (CCI.actualstepid<>WS.WORKFLOWSTEPID OR CCI.actualstepid IS NULL) AND ((C.ORIGINALSTARTDATE>TO_DATE('2017/11/05','yyyy/MM/dd') AND C.ORIGINALFACTORYID <>'0004e2800000001c') OR C.ORIGINALFACTORYID='0004e2800000001c') ");//OR C.QTY<>CCI.QTY 
            strSql += " where C.ORIGINALSTARTDATE>TO_DATE('2017/11/05','yyyy/MM/dd') and rownum<101 ";
            strSql += @" GROUP BY C.QTY,C.STATUS,WFB.WORKFLOWNAME,WF.WORKFLOWREVISION,WF.WORKFLOWBASEID,C.CONTAINERTYPE,
WF.WORKFLOWID,WS.WORKFLOWSTEPID,cci.workflowid ,CCI.WORKFLOWSTEPID,WS.WORKFLOWSTEPNAME,CCI.WORKFLOWSTEPSEQUENCE ,WS.SEQUENCE ,SB2.SPECNAME,
S.SPECREVISION,S.DESCRIPTION ,S.SPECID,S.SPECBASEID,S.ISKEY,s.lastcheck,S.SPECNO,S.PARENTSPECNO,
S.FACTORYID ,C.CONTAINERID,C.CONTAINERNAME,CCI.ISINSTORE,CCI.WORKCENTERDISPATCHID,CCI.Shipnum,cci.shipid,
CCI.Originalfactoryid,fa.factoryname ,cci.fromworkcenterid,cci.fromworkcentername,CCI.bomid ,
P.description ,C.splitfromid,CDO.CDONAME,WS.WORKFLOWSTEPID ,cci.actualstepid ,nvl(s.controlcode,ws.controlcode) ";
            DataSet myDt = DatabaseHelper.Query(strSql);
            if (myDt == null || myDt.Tables.Count == 0)
            {
                return null;
            }
            return myDt.Tables[0];

        }
        /// <summary>
        /// 更新工序基本信息
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private Boolean UpdateSpecBaseInfoOfRow(DataRow dr)
        {
            string updateSql = @"UPDATE CONTAINERCURRENTINFO C
	            SET QTY= :QTY,
			 CONTAINERSTATUS = :CONTAINERSTATUS,
			 WORKFLOWNAME = :WORKFLOWNAME,
			 WORKFLOWREVISION = :WORKFLOWREVISION,
			 WORKFLOWBASEID = :WORKFLOWBASEID,
			 WORKFLOWID  = :WORKFLOWID,
			 WORKFLOWSTEPID = :WORKFLOWSTEPID,
			 WORKFLOWSTEPNAME  = :WORKFLOWSTEPNAME,
			 WORKFLOWSTEPSEQUENCE = :WORKFLOWSTEPSEQUENCE,
			 SPECNAME  = :SPECNAME,
			 SPECREVISION  = :SPECREVISION,
			 SPECDESCRIPTION = :SPECDESCRIPTION,
			 SPECID    = :SPECID,
			 SPECBASEID   = :SPECBASEID,
			 ISKEY  = :ISKEY,
			 SPECNO= :SPECNO,
			 PARENTSPECNO   = :PARENTSPECNO,
			 SPECFACTORYID = :SPECFACTORYID,
             ISINSTORE=:ISINSTORE,
            productdescription=:productdescription,
            actualstepid=:actualstepid";

            updateSql += " ,workreportnum=0,AllLossQty=0,stepchecknum=0,firstchecknum=0,CanDispatchNum=:QTY,NONCONFORMINGNUM=NULL";
            //移到下工序情况
            // if (Convert.IsDBNull(dr["CCIWORKFLOWSTEPID"]) == false && Convert.ToString(dr["WORKFLOWSTEPID"]) != Convert.ToString(dr["CCIWORKFLOWSTEPID"]) && (Convert.ToInt64(dr["CCIWORKFLOWSTEPSEQUENCE"]) + 1 == Convert.ToInt64(dr["WORKFLOWSTEPSEQUENCE"]))) //移到下一工序的情况
            //{

            #region 派工标记位处理
            //string strDispachSql = string.Format(" SELECT csd.workflowstepid FROM CONTAINERSTEPDISPATCH CSD" +
            //                    " LEFT JOIN WORKFLOWSTEP WS ON WS.WORKFLOWSTEPID=CSD.WORKFLOWSTEPID" +
            //                    " WHERE WS.SEQUENCE>={0} AND WS.WORKFLOWID='{1}' AND CSD.CONTAINERID='{2}' AND CSD.ISUSE = 0 and rownum<6",
            //                    Convert.ToInt64(dr["WORKFLOWSTEPSEQUENCE"]), Convert.ToString(dr["WORKFLOWID"]), Convert.ToString(dr["CONTAINERID"]));

            string strDispachSql = string.Format("SELECT csd.workflowstepid FROM CONTAINERSTEPDISPATCH CSD " +
                   "WHERE  CSD.CONTAINERID='{0}'  AND CSD.ISUSE = 0 " +
                   "AND EXISTS ( " +
                   "SELECT 1 FROM workflowstep ws WHERE ws.workflowstepid=csd.workflowstepid AND ws.workflowid='{1}' AND ws.sequence>={2} " +
                   ") AND ROWNUM<=2", Convert.ToString(dr["CONTAINERID"]), Convert.ToString(dr["WORKFLOWID"]), Convert.ToInt64(dr["WORKFLOWSTEPSEQUENCE"]));
            DataTable dispachData = DatabaseHelper.Query_ReturnDatTable(strDispachSql);
            if (dispachData.Rows.Count == 0) //判断下道工序及之后是否还有派工记录,无派工记录
            {
                updateSql += " ,IsDispatch=0 ,dispatchnum=0";
            }
            else
            {
                updateSql += ",dispatchnum=1";
                if (dispachData.Select("workflowstepid='" + dr["WORKFLOWSTEPID"].ToString() + "'").Length > 0)//下序有派工
                    updateSql += ",IsDispatch=1";
                else
                    updateSql += ",IsDispatch=0";
            }
            #endregion

            #region 工区协作处理
            //if (Convert.IsDBNull(dr["WORKCENTERDISPATCHID"]) == false) //如果是协作工区的流水卡
            //{
            string strSql2 = string.Format(" SELECT CWD.WORKFLOWSTEPID,cwd.recvdate,cwd.containerworkcenterdispatchid,cwd.toworkcenterid FROM CONTAINERWORKCENTERDISPATCH CWD " +
                                         " LEFT JOIN WORKFLOWSTEP WS ON WS.WORKFLOWSTEPID=CWD.WORKFLOWSTEPID" +
                                            " WHERE CWD.CONTAINERID='{0}' AND WS.SEQUENCE>={1} AND ws.workflowid='{2}' AND CWD.ISUSE=0 ",
                                            Convert.ToString(dr["CONTAINERID"]), Convert.ToString(dr["WorkflowStepSequence"]), dr["WORKFLOWID"].ToString());
            DataTable wcDt = DatabaseHelper.Query_ReturnDatTable(strSql2);
            if (wcDt.Rows.Count == 0)//下道序之后不存在工区协作
            {
                updateSql += " ,workcenterdispatchid='',WORKCENTERDISPATCHNUM=0,toworkcenterid=''";//,TEAMID='',TEAMNAME='',Teamdispatchid='',Teamdispatchnum=0 去掉
            }//如果存在协作工区的话可能要写入些字段
            else
            {
                DataRow[] tempDrs = wcDt.Select(string.Format("WORKFLOWSTEPID='{0}'", dr["WORKFLOWSTEPID"].ToString()));
                DataRow[] drs = wcDt.Select(string.Format("recvdate is not null"));
                if (tempDrs.Length > 0) //当前序有工区协作
                {
                    updateSql += string.Format(" ,workcenterdispatchid='{0}'", tempDrs[0]["containerworkcenterdispatchid"].ToString());
                    //if (string.IsNullOrWhiteSpace(tempDrs[0]["recvdate"].ToString()))//是否已接收
                    //{
                    //    updateSql += " ,WORKCENTERDISPATCHNUM=1,toworkcenterid=''";
                    //}
                    //else
                    //{
                    //    updateSql += string.Format(" ,WORKCENTERDISPATCHNUM=0,toworkcenterid='{0}'", tempDrs[0]["toworkcenterid"].ToString());
                    //}
                }
                else //当前序后的其他序有工区协作
                {
                    updateSql += " ,workcenterdispatchid=''";
                }
                if (drs.Length == wcDt.Rows.Count)//全部接收
                {
                    updateSql += string.Format(",WORKCENTERDISPATCHNUM=0,toworkcenterid='{0}'", wcDt.Rows[0]["toworkcenterid"].ToString());
                }
                else if (drs.Length < wcDt.Rows.Count) //部分接收
                { updateSql += string.Format(",WORKCENTERDISPATCHNUM=1,toworkcenterid='{0}'", wcDt.Rows[0]["toworkcenterid"].ToString()); }
                else
                {
                    updateSql += " ,WORKCENTERDISPATCHNUM=1,toworkcenterid=''";
                }

            }
            //}
            //
            #endregion

            #region 外委标记为处理

            //判断清除外委的字段
            string commissionSql = string.Format(@"SELECT ws.workflowstepid,ccni.containerid,ccni.containercommissioningid FROM ContainerCommissioning ccni
left join containercommidetail cl on cl.containercommissioningid=ccni.containercommissioningid
left join workflowstep ws on ws.workflowstepid=cl.workflowstepid
WHERE ccni.containerid='{0}' AND ws.workflowid='{1}' and ccni.isuse=0 and ws.sequence>={2}",
                                               Convert.ToString(dr["CONTAINERID"]), Convert.ToString(dr["WORKFLOWID"]), Convert.ToInt64(dr["WORKFLOWSTEPSEQUENCE"]));
            DataTable commissionData = DatabaseHelper.Query_ReturnDatTable(commissionSql);
            if (commissionData.Rows.Count == 0)//判断下序是否存在外委，不存在情况
            {
                updateSql += " ,ISCOMMISSIONING=0,Commissioningnum=0";
            }
            else
            {
                updateSql += " ,Commissioningnum=1";
                if (commissionData.Select("workflowstepid='" + dr["WORKFLOWSTEPID"].ToString() + "'").Length > 0)//下序有外委
                    updateSql += " ,ISCOMMISSIONING=1";
                else
                    updateSql += ",ISCOMMISSIONING=0";
            }

            #endregion

            #region BOM字段处理
            if (Convert.ToString(dr["WORKFLOWSTEPNAME"]) != "完工入库" && dr["cdoname"].ToString() == "MachineMfgWorkFlow" && dr["cciworkflowid"].ToString() != dr["workflowid"].ToString())
            {
                var newBomid = DatabaseHelper.GetSingle(string.Format(@"SELECT MAX(b.bomid) bomid FROM bom b WHERE b.workflowid='{0}'", dr["workflowid"].ToString()));
                if (newBomid == null)
                {
                    updateSql += ",BOMID=''";
                }
                else
                {
                    updateSql += ",BOMID='" + newBomid.ToString() + "'";
                }
            }
            #endregion

            //
            //string teamUpdateSql = UpdateTeamInfoOfNextSpec(dr);
            //updateSql += teamUpdateSql;
            #region 转工字段处理
            //有转工记录，进行相关字段检查 update:wangjh 20230707
            if (!dr.IsNull("shipid"))//有转工申请
            {
                string shipSql = @"select wc.workcentername toworkcentername,fa.factoryname tofactoryname,csr.*  from containershiprecord csr
left join factory fa on fa.factoryid=csr.tofactoryid left join workcenter wc on wc.workcenterid=csr.toworkcenterid WHERE  csr.containershiprecordid='" + dr["shipid"].ToString() + "'";
                //shipSql += " and csr.workflowstepid='" + dr["WORKFLOWSTEPID"].ToString() + "'";
                DataTable shipDt = DatabaseHelper.Query_ReturnDatTable(shipSql);

                DataTable shipRecDt = DatabaseHelper.Query_ReturnDatTable(string.Format(@"select * from containershiprecive csre where  csre.containershiprecordid='{0}' and csre.containerid='{1}'",
                    dr["shipid"].ToString(), dr["containerid"].ToString()));

                var _shipFileds = ",shipnum={0},isship={1},shipid='{2}',FACTORYID='{3}',FACTORYName='{4}',WORKCENTERID='{5}',WORKCENTERname='{6}'";

                var shipNum = dr["shipnum"].ToString();
                var isship = 1; var shipId = dr["shipid"].ToString();
                var faId = dr["originalfactoryid"].ToString();
                var faName = dr["originalfactoryname"].ToString();
                var wcId = dr["fromworkcenterid"].ToString();
                var wcName = dr["fromworkcentername"].ToString();

                //进行字段更新判断
                if (shipDt.Rows.Count > 0)
                {
                    var _shipDr = shipDt.Rows[0];
                    var _shipRevDr = shipRecDt.NewRow();
                    if (shipRecDt.Rows.Count > 0)
                        _shipRevDr = shipRecDt.Rows[0];
                    if (_shipDr["isuse"].ToString() == "1")
                    {
                        shipNum = "0"; isship = 0; shipId = "";
                    }
                    else//有效情况
                    {
                        if (!_shipDr.IsNull("PREPOSERDATE"))//有申请日期
                        {
                            shipNum = "1";
                        }
                        if (!_shipDr.IsNull("auditdate"))//有审核日期
                        {
                            shipNum = "2";
                            if (_shipDr["AUDITRESULT"].ToString() == "1")//不同意
                            {
                                shipNum = "0"; isship = 0; shipId = "";
                            }
                            if (_shipDr["AUDITRESULT"].ToString() == "0" && _shipDr["workflowstepid"].ToString() == dr["workflowstepid"].ToString())//审核同意且转工第一序和当前序一致
                            {
                                shipNum = "3";
                            }
                        }
                        if (!_shipDr.IsNull("SENDER"))//有转出日期
                        {
                            shipNum = "4";
                            faId = _shipDr["tofactoryid"].ToString();
                            faName = _shipDr["tofactoryname"].ToString();
                        }
                        if (!_shipDr.IsNull("ToAcceptDate"))//有承制接收日期
                        {
                            shipNum = "5";
                            wcId = _shipDr["toworkcenterid"].ToString();
                            wcName = _shipDr["toworkcentername"].ToString();
                            if (dr["WORKFLOWSTEPID"].ToString() == _shipDr["TOWORKFLOWSTEPID"].ToString())//当前序等于转工最后一序
                            {
                                shipNum = "6";
                            }
                        }
                        if (!_shipRevDr.IsNull("CompleteDate"))//有承制完成日期
                        {
                            shipNum = "7";
                        }
                        if (!_shipRevDr.IsNull("ReciveDate"))//有主制转回日期
                        {
                            shipNum = "8";
                            isship = 0; shipId = "";
                            faId = dr["originalfactoryid"].ToString();
                            faName = dr["originalfactoryname"].ToString();
                            wcId = dr["fromworkcenterid"].ToString();
                            wcName = dr["fromworkcentername"].ToString();
                        }

                    }
                }

                updateSql += string.Format(_shipFileds, shipNum, isship, shipId, faId, faName, wcId, wcName);

                //查询是否到转工已申请的序                
                //if (shipDt.Rows.Count > 0) {
                //    if (dr["shipnum"].ToString() == "2" && dr["WORKFLOWSTEPID"].ToString() == shipDt.Rows[0]["WORKFLOWSTEPID"].ToString ())//提前申请的
                //    {
                //        updateSql += ",shipnum=3";
                //    }
                //    if (dr["shipnum"].ToString() == "5" && dr["WORKFLOWSTEPID"].ToString() == shipDt.Rows[0]["TOWORKFLOWSTEPID"].ToString ())//承制分厂加工到转工最后一道的
                //    {
                //        updateSql += ",shipnum=6";
                //    }
                //}
                //
            }
            //

            #endregion

            updateSql += " WHERE C.CONTAINERID=:CONTAINERID";

            OracleParameter[] updateParam = new OracleParameter[22];
            updateParam[0] = new OracleParameter(":QTY", OracleType.Number);
            updateParam[0].Direction = ParameterDirection.Input;
            updateParam[0].Value = dr["QTY"];

            updateParam[1] = new OracleParameter(":CONTAINERSTATUS", OracleType.Number);
            updateParam[1].Direction = ParameterDirection.Input;
            updateParam[1].Value = dr["CONTAINERSTATUS"];

            updateParam[2] = DatabaseHelper.NewParameter(":WORKFLOWNAME", dr["WORKFLOWNAME"], OracleType.VarChar);
            updateParam[3] = DatabaseHelper.NewParameter(":WORKFLOWREVISION", dr["WORKFLOWREVISION"], OracleType.VarChar);
            updateParam[4] = DatabaseHelper.NewParameter(":WORKFLOWBASEID", dr["WORKFLOWBASEID"], OracleType.VarChar);
            updateParam[5] = DatabaseHelper.NewParameter(":WORKFLOWID", dr["WORKFLOWID"], OracleType.VarChar);
            updateParam[6] = DatabaseHelper.NewParameter(":WORKFLOWSTEPID", dr["WORKFLOWSTEPID"], OracleType.VarChar);
            updateParam[7] = DatabaseHelper.NewParameter(":WORKFLOWSTEPNAME", dr["WORKFLOWSTEPNAME"], OracleType.VarChar);

            updateParam[8] = new OracleParameter(":WORKFLOWSTEPSEQUENCE", OracleType.Number);
            updateParam[8].Direction = ParameterDirection.Input;
            updateParam[8].Value = dr["WORKFLOWSTEPSEQUENCE"];

            updateParam[9] = DatabaseHelper.NewParameter(":SPECNAME", dr["SPECNAME"], OracleType.VarChar);
            updateParam[10] = DatabaseHelper.NewParameter(":SPECREVISION", dr["SPECREVISION"], OracleType.VarChar);
            updateParam[11] = DatabaseHelper.NewParameter(":SPECDESCRIPTION", dr["SPECDESCRIPTION"], OracleType.VarChar);
            updateParam[12] = DatabaseHelper.NewParameter(":SPECID", dr["SPECID"], OracleType.VarChar);
            updateParam[13] = DatabaseHelper.NewParameter(":SPECBASEID", dr["SPECBASEID"], OracleType.VarChar);
            updateParam[14] = DatabaseHelper.NewParameter(":ISKEY", dr["ISKEY"], OracleType.VarChar);
            updateParam[15] = DatabaseHelper.NewParameter(":SPECNO", dr["SPECNO"], OracleType.VarChar);
            updateParam[16] = DatabaseHelper.NewParameter(":PARENTSPECNO", dr["PARENTSPECNO"], OracleType.VarChar);
            updateParam[17] = DatabaseHelper.NewParameter(":SPECFACTORYID", dr["SPECFACTORYID"], OracleType.VarChar);
            updateParam[18] = DatabaseHelper.NewParameter(":CONTAINERID", dr["CONTAINERID"], OracleType.VarChar);
            if (Convert.ToString(dr["WORKFLOWSTEPNAME"]) == "完工入库")
            {
                dr["ISINSTORE"] = 1;
            }
            else if (dr["cdoname"].ToString() == "MachineMfgWorkFlow")
            {
                dr["ISINSTORE"] = 0;
            }

            updateParam[19] = DatabaseHelper.NewParameter(":ISINSTORE", Convert.ToInt64(dr["ISINSTORE"]), OracleType.Number);
            updateParam[20] = DatabaseHelper.NewParameter(":productdescription", dr["productdescription"], OracleType.VarChar);
            updateParam[21] = DatabaseHelper.NewParameter(":actualstepid", dr["actualstepid"], OracleType.VarChar);
            int i = DatabaseHelper.ExecuteSql(updateSql, updateParam);
            //InsertOracleLog(System.Reflection.MethodBase.GetCurrentMethod().Name, "更新工序信息", i, LogHelp.TranferSql(updateSql, updateParam), dr["CONTAINERNAME"].ToString());
            if (i > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 更新工序所有信息
        /// </summary>
        /// <param name="dr"></param>
        void UpdateSpecInfoOfRow(DataRow dr)
        {
            //为处理更新工序信息出错填写日志 add tianFW 2018年5月23日
            try
            {
                if (UpdateSpecBaseInfoOfRow(dr) == false)
                {
                    LogHelp.WriteLog("批次：" + dr["ContainerID"].ToString() + " " + dr["WORKFLOWSTEPID"].ToString() + " 处理更新工序信息出错（如果是工序检则不再自动添加报工记录）");
                    return;
                }
            }
            catch (Exception e)
            {
                LogHelp.WriteLog("批次：" + dr["ContainerID"].ToString() + " " + dr["WORKFLOWSTEPID"].ToString() + " 处理更新工序信息出错（如果是工序检则不再自动添加报工记录):" + e.Message);
                return;
            }
            if (dr["ISINSTORE"].ToString() == "-1")//非在制工艺的流水卡不用以下判断 add:Wangjh 20180402
            {
                return;
            }
            if (!dr.IsNull("splitfromid"))//如果是分批出来的卡判断是否需要做转工标记
            {
                UpdateSplitContainerShip(dr);//更新原批次的转工标记
            }
            //自动转工放在此 add:Wangjh 20180717
            try { SupplyAutoShip(dr); }
            catch (Exception e) { LogHelp.WriteLog(e.Message); }
            //
            //2018年6月25日 增加分厂'检验工序自动报工'属性判断
            String factoryvalue = m_Common.GetFatoryAttributes(dr["SpecFactoryID"].ToString(), "检验序自动报工");//update:Wangjh 20181207 分厂参数改为工序分厂
            if (factoryvalue == "是" && dr["LASTCHECK"].ToString() == "1" && dr["controlcode"].ToString() != "LY05")
            {   //tianFW add 2017-06-27  检验下一序是否是检验序
                if (AddContainerStepWorkReportInfo(dr))
                {
                    //LogHelp.WriteLog("批次检验序：" + dr["ContainerID"].ToString() + " " + dr["WORKFLOWSTEPID"].ToString() + " 添加报工记录成功");
                }
            }
            //更新workreportnum
            m_Workreport.UpdateWorkReportNum(dr["ContainerID"].ToString());
            try
            {
                lock (teamDispatchLock)
                {
                    //处理自动班组派工,班组相关字段
                    AutoContainerTeamDispatchInfo(dr);
                }
            }
            catch (Exception ex)
            {
                LogHelp.WriteError("批次自动班组派工信息:" + dr["ContainerID"].ToString() + " " + dr["WORKFLOWSTEPID"].ToString() + ex.Message, ex);
            }
            UpdateTeamInfoOfNextSpec(dr);//更新班组派工相关字段
            UpdateConWorkcenterIdsAndTeamids(dr);//更新teamids和workcenterids

            //处理需要推送给erp的记录
            if (dr["cciworkflowid"].ToString() != dr["workflowid"].ToString() && dr["CDONAME"].ToString() == "MachineMfgWorkFlow")
            {
                WriteToErpWorkflowInfo(dr);
            }
        }

        /// <summary>
        /// 给erp的工艺信息
        /// add:Wangjh 20230302
        /// </summary>
        /// <param name="dr"></param>
        void WriteToErpWorkflowInfo(DataRow dr)
        {
            var strSql = @"select  mv.* from movehistory mv where movehistoryid in 
(select max(a.movehistoryid) maxmovehistoryid from movehistory a where a.historyid='{0}')";

            var dt = DatabaseHelper.Query_ReturnDatTable(string.Format(strSql, dr["containerid"].ToString()));

            strSql = @"insert into SendToErpWorkflowInfo sw (sw.containerid,sw.workflowid,sw.issenderp,sw.sendtoerpworkflowinfoid,sw.createdate,
sw.createempid) values ('{0}','{1}',0,sys_guid(),sysdate,'{2}')";
            if (dt.Rows.Count > 0)
            {
                if (dt.Rows[0]["notes"] == "MoveBack")
                    return;
                DatabaseHelper.ExecuteSql(string.Format(strSql, dr["containerid"], dr["workflowid"], dt.Rows[0]["reportemployeeid"].ToString()));
            }
            else
            {
                DatabaseHelper.ExecuteSql(string.Format(strSql, dr["containerid"], dr["workflowid"], DatabaseHelper.GetSingle("SELECT c.startemployeeid FROM container c WHERE c.containerid='" + dr["containerid"].ToString() + "'").ToString()));
            }
        }

        /// <summary>
        /// 循环更新工序信息
        /// </summary>
        /// <param name="containerData"></param>
        /// <returns></returns>
        public Boolean UpdateSpecInfo()
        {
            DataTable containerData = GetSpecInfo();
            if (containerData.Rows.Count > 0)
            {
                //foreach (DataRow dr in containerData.Rows)
                //{
                //   UpdateSpecInfoOfRow(dr);
                //}

                //Parallel.For(0, containerData.Rows.Count, new ParallelOptions() {MaxDegreeOfParallelism = Environment.ProcessorCount}, (int i) =>
                //{
                //    UpdateSpecInfoOfRow(containerData.Rows[i]);
                //});

                //转化为线程安全对象
                ConcurrentBag<DataRow> cd = new ConcurrentBag<DataRow>();
                foreach (DataRow dr in containerData.Rows)
                {
                    cd.Add(dr);
                }
                Parallel.ForEach(cd, new ParallelOptions() { MaxDegreeOfParallelism = Environment.ProcessorCount }, (item, ParallelLoopState) =>
                {
                    UpdateSpecInfoOfRow(item);
                });

            }

            return true;
        }

        /// <summary>
        /// 判断一本工艺是否另一本的子工艺
        /// </summary>
        /// <param name="cciworkflowID"></param>
        /// <param name="workflowID"></param>
        /// <returns></returns>
        DataTable specialStepOfSubWorkflow(string containerID, string stepID, string cciStepID, string workflowID)
        {
            DataTable result = new DataTable();
            string strSql = @"SELECT ws.workflowstepid,w.factoryid specfactoryid  FROM workflowstep ws
                            LEFT JOIN workflowbase wb ON wb.workflowbaseid=ws.subworkflowbaseid
                            LEFT JOIN workflow w ON w.workflowid=NVL(wb.revofrcdid,ws.subworkflowid)
                            ";
            strSql += string.Format(" WHERE  w.workflowid='{0}'", workflowID);
            DataTable dt = DatabaseHelper.Query_ReturnDatTable(strSql);
            if (dt.Rows.Count == 0)
                return result;
            strSql = @"
                    SELECT ws.workflowstepid,ws.workflowstepname,SUBSTR(ws.workflowstepname,0,INSTR(ws.workflowstepname,'-')-1) specno,ws.sequence,W.WORKFLOWID,WB.WORKFLOWBASEID,WB.WORKFLOWNAME,W.WORKFLOWREVISION  FROM Movehistory mh
                    LEFT JOIN historymainline hml ON hml.historymainlineid=mh.historymainlineid
                    LEFT JOIN Workflowstep ws ON ws.workflowstepid=mh.notes
                    LEFT JOIN WORKFLOW W ON W.WORKFLOWID=WS.WORKFLOWID
					LEFT JOIN WORKFLOWBASE WB ON WB.WORKFLOWBASEID=W.WORKFLOWBASEID
                    WHERE hml.reversalstatus=1 and mh.notes<>mh.tostepid
                    ";
            strSql += string.Format(" AND  mh.historyid='{0}' AND mh.stepid='{1}' AND mh.tostepid='{2}' ", containerID, cciStepID, stepID);
            strSql += " ORDER BY mh.movehistoryid DESC";

            result = DatabaseHelper.Query_ReturnDatTable(strSql);
            result.Columns.Add("specfactoryid");
            if (result.Rows.Count > 0)
                result.Rows[0]["specfactoryid"] = dt.Rows[0]["specfactoryid"];
            return result;
        }
        #endregion

        #region 更新数量信息 create:Wangjh
        /// <summary>
        /// 获取在制数变化的批次
        /// </summary>
        /// <returns></returns>
        private DataTable GetQtyOfContainer()
        {
            string strSql = @" SELECT C.QTY,CCI.QTY AS CCIQTY,CCI.CONTAINERID,C.CONTAINERTYPE,CCI.CONTAINERTYPE CCICONTAINERTYPE,CCI.WORKFLOWSTEPID,c.containername,c.togetherflag FROM CONTAINER C
                               INNER JOIN CONTAINERCURRENTINFO CCI ON CCI.CONTAINERID=C.CONTAINERID
                               WHERE NVL( CCI.QTY,0)<>C.QTY OR (CCI.CONTAINERTYPE<>C.CONTAINERTYPE)--单件单卡变更";
            DataTable dt = DatabaseHelper.Query_ReturnDatTable(strSql);
            if (dt == null)
            {
                return null;
            }
            return dt;
        }
        /// <summary>
        /// 更新每行的数量
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private Boolean UpdateContainerQtyOfRow(DataRow dr)
        {
            string updateSql = @" UPDATE CONTAINERCURRENTINFO C
                                   SET QTY= :QTY,C.CONTAINERTYPE=:CONTAINERTYPE,c.togetherflag=:togetherflag";
            if (dr["CCICONTAINERTYPE"].ToString() == "7")
                updateSql += " ,c.containerno=''";
            updateSql += " WHERE C.CONTAINERID=:CONTAINERID";
            OracleParameter[] updateParam = new OracleParameter[4];
            updateParam[0] = DatabaseHelper.NewParameter(":QTY", dr["QTY"], OracleType.Number);
            updateParam[1] = DatabaseHelper.NewParameter(":CONTAINERID", dr["CONTAINERID"], OracleType.VarChar);
            updateParam[2] = DatabaseHelper.NewParameter(":CONTAINERTYPE", dr["CONTAINERTYPE"], OracleType.Number);
            updateParam[3] = DatabaseHelper.NewParameter(":togetherflag", dr["togetherflag"], OracleType.VarChar);
            int i = DatabaseHelper.ExecuteSql(updateSql, updateParam);
            InsertOracleLog(System.Reflection.MethodBase.GetCurrentMethod().Name, "更新数量信息", i, LogHelp.TranferSql(updateSql, updateParam), dr["CONTAINERNAME"].ToString());
            if (i > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 更新自动转工、检验和外委的数量变化信息
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private void UpdateAutoInfo(DataRow dr)
        {
            string updateSql = string.Format("UPDATE containerstepworkreport csw SET csw.qty={0}," +
                                           " csw.istransfer=0 WHERE csw.containerid='{1}' AND csw.workflowstepid='{2}' AND csw.workerid IS NULL",
                                           dr["QTY"], dr["CONTAINERID"], dr["WORKFLOWSTEPID"]);
            if (IsChecked(dr["CONTAINERID"].ToString(), dr["WORKFLOWSTEPID"].ToString()) == false) //非检验变更数量才改
                DatabaseHelper.ExecuteSql(updateSql);//更新自动报工数量
            updateSql = string.Format("UPDATE containercommissioning  cmm SET cmm.outqty={0} " +
                                    "WHERE cmm.containerid='{1}' AND cmm.workflowstepid='{2}' AND cmm.outemployeeid IS NULL",
                                    dr["QTY"], dr["CONTAINERID"], dr["WORKFLOWSTEPID"]);
            DatabaseHelper.ExecuteSql(updateSql);//更新自动外委数量

        }

        /// <summary>
        /// 更新所有数量
        /// </summary>
        /// <returns></returns>
        public Boolean UpdateContainerQtyInfo()
        {
            DataTable containerData = GetQtyOfContainer();
            if (containerData.Rows.Count > 0)
            {
                foreach (DataRow dr in containerData.Rows)
                {
                    if (UpdateContainerQtyOfRow(dr) == false)
                    {
                        return false;
                    }
                    UpdateAutoInfo(dr);//更新自动外委，自动报工的数量
                }
            }

            return true;
        }
        /// <summary>
        /// 是否存在检验
        /// </summary>
        /// <param name="containerID"></param>
        /// <param name="stepID"></param>
        /// <returns></returns>
        Boolean IsChecked(string containerID, string stepID)
        {

            string strSql = string.Format(@"SELECT cqc.*  FROM checkqtychangerecord cqc
                                LEFT JOIN containerstepworkreport csw ON csw.containerstepworkreportid=cqc.containerstepworkreportid AND csw.isuse=0
                                        WHERE cqc.isuse=0  AND  csw.containerid='{0}' AND csw.workflowstepid='{1}'",
                containerID, stepID);
            if (DatabaseHelper.Query_ReturnDatTable(strSql).Rows.Count == 0)
            {
                return false;
            }
            else { return true; }

        }

        #endregion

        #region 更新班组信息 creat:Wangjh
        /// <summary>
        /// 获取派到班组信息
        /// </summary>
        /// <returns></returns>
        private DataTable GetTeamDispachInfo()
        {
            string strSql = @" SELECT DISTINCT T.TEAMNAME,CTD.TEAMID,CTD.CONTAINERTEAMDISPATCHID AS TEAMDISPATCHID,CCI.CONTAINERNAME,
                               DECODE(CTD.CONTAINERTEAMDISPATCHID, NULL, 0, 1) TEAMDISPATCHNUM,CTD.CONTAINERID,CTD.ISUSE,
                               CTD.ISTRANSFER,CTD.WORKFLOWSTEPID,CCI.WORKFLOWSTEPID CUWORKFLOWSTEPID,CCI.TEAMID CCITEAMID,CCI.TEAMNAME CCITEAMNAME, 
                               CCI.WORKFLOWSTEPSEQUENCE,CCI.WORKFLOWID,CCI.CONTAINERNAME
                               FROM CONTAINERTEAMDISPATCH CTD 
                               INNER JOIN CONTAINERCURRENTINFO CCI ON CCI.CONTAINERID = CTD.CONTAINERID	
                               LEFT JOIN TEAM T ON T.TEAMID=CTD.TEAMID																                              
                               WHERE CTD.ISTRANSFER=0 ";
            DataSet myDt = DatabaseHelper.Query(strSql);
            if (myDt == null || myDt.Tables.Count == 0)
            {
                return null;
            }
            return myDt.Tables[0];
        }
        /// <summary>
        /// 更新班组派工信息
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        public Boolean UpdateTeamDispachOfRow(DataRow dr)
        {
            string updateSql = @"UPDATE CONTAINERCURRENTINFO C SET TEAMNAME=:TEAMNAME,TEAMID=:TEAMID,TEAMDISPATCHID=:TEAMDISPATCHID,
                                  TEAMDISPATCHNUM=:TEAMDISPATCHNUM
                                  WHERE C.CONTAINERID=:CONTAINERID";
            OracleParameter[] updateParam = new OracleParameter[5];
            updateParam[0] = DatabaseHelper.NewParameter(":TEAMNAME", dr["TEAMNAME"], OracleType.VarChar);
            updateParam[1] = DatabaseHelper.NewParameter(":TEAMID", dr["TEAMID"], OracleType.VarChar);
            updateParam[2] = DatabaseHelper.NewParameter(":TEAMDISPATCHID", dr["TEAMDISPATCHID"], OracleType.VarChar);
            updateParam[3] = DatabaseHelper.NewParameter(":CONTAINERID", dr["CONTAINERID"], OracleType.VarChar);

            updateParam[4] = new OracleParameter(":TEAMDISPATCHNUM", OracleType.Number);
            updateParam[4].Direction = ParameterDirection.Input;
            updateParam[4].Value = dr["TEAMDISPATCHNUM"];
            int i = DatabaseHelper.ExecuteSql(updateSql, updateParam);
            InsertOracleLog(System.Reflection.MethodBase.GetCurrentMethod().Name, "更新班组信息", i, LogHelp.TranferSql(updateSql, updateParam), dr["CONTAINERNAME"].ToString());
            if (i > 0)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
        /// <summary>
        /// 循环更新班组派工信息
        /// </summary>
        /// <param name="containerData"></param>
        /// <returns></returns>
        public Boolean UpdateTeamDispach()
        {
            DataTable containerData = GetTeamDispachInfo();

            DataView tempDv = containerData.DefaultView;
            tempDv.RowFilter = " WORKFLOWSTEPID=CUWORKFLOWSTEPID AND ISUSE=0";//筛选当前工序的班组派工
            DataTable tempDt = tempDv.ToTable();

            DataView tempDv2 = containerData.DefaultView;
            tempDv2.RowFilter = " WORKFLOWSTEPID IS NOT NULL AND  WORKFLOWSTEPID<>CUWORKFLOWSTEPID AND ISUSE=0";//筛选不是当前工序的班组派工
            DataTable tempDt2 = tempDv2.ToTable();

            DataView tempDv3 = containerData.DefaultView;
            tempDv3.RowFilter = " WORKFLOWSTEPID IS  NULL AND ISUSE=0 ";//筛选批次班组派工
            DataTable tempDt3 = tempDv3.ToTable();

            DataView tempDv4 = containerData.DefaultView;
            tempDv4.RowFilter = "  ISUSE=1 ";//筛选移除的班组派工
            DataTable tempDt4 = tempDv4.ToTable();

            DataView tempDv5 = containerData.DefaultView;
            tempDv5.RowFilter = "";
            DataTable tempDt5 = tempDv5.ToTable(true, "CONTAINERID", "WORKFLOWID", "WORKFLOWSTEPSEQUENCE");

            if (tempDt4.Rows.Count > 0)//更新移除班组派工信息
            {
                foreach (DataRow dr in tempDt4.Rows)
                {
                    if (UpdateTransferOfTable("CONTAINERTEAMDISPATCH", "CONTAINERTEAMDISPATCHID", dr["TEAMDISPATCHID"]) == false) //更新批次班组派工表的结转标记
                    {
                        return false;
                    }
                    dr["TEAMNAME"] = ""; dr["TEAMID"] = ""; dr["TEAMDISPATCHID"] = ""; dr["TEAMDISPATCHNUM"] = 0;

                    if (UpdateTeamDispachOfRow(dr) == false)
                    {
                        return false;
                    }

                }
            }


            if (tempDt3.Rows.Count > 0)//更新批次班组派工信息
            {
                foreach (DataRow dr in tempDt3.Rows)
                {
                    if (UpdateTeamDispachOfRow(dr) == false)
                    {
                        return false;
                    }

                    if (Convert.IsDBNull(dr["TEAMDISPATCHID"]) == false && !string.IsNullOrWhiteSpace(dr["TEAMDISPATCHID"].ToString()))
                    {
                        string tableName = "CONTAINERTEAMDISPATCH";
                        if (UpdateTransferOfTable(tableName, "CONTAINERTEAMDISPATCHID", dr["TEAMDISPATCHID"]) == false) //更新批次班组派工表的结转标记
                        {
                            return false;
                        }
                    }
                }
            }

            if (tempDt2.Rows.Count > 0)//更新不是当前工序班组派工信息
            {
                foreach (DataRow dr in tempDt2.Rows)
                {
                    if (UpdateTransferOfTable("CONTAINERTEAMDISPATCH", "CONTAINERTEAMDISPATCHID", dr["TEAMDISPATCHID"]) == false) //更新批次班组派工表的结转标记
                    {
                        return false;
                    }
                    if (!string.IsNullOrWhiteSpace(dr["CCITEAMID"].ToString()))
                    {
                        dr["TEAMNAME"] = dr["CCITEAMNAME"]; dr["TEAMID"] = dr["CCITEAMID"]; dr["TEAMDISPATCHID"] = ""; dr["TEAMDISPATCHNUM"] = 1;
                    }
                    else
                    {
                        dr["TEAMNAME"] = ""; dr["TEAMID"] = ""; dr["TEAMDISPATCHID"] = ""; dr["TEAMDISPATCHNUM"] = 1;
                    }

                    if (UpdateTeamDispachOfRow(dr) == false)
                    {
                        return false;
                    }
                }
            }

            if (tempDt.Rows.Count > 0)//更新当前工序班组派工信息
            {
                foreach (DataRow dr in tempDt.Rows)
                {
                    if (UpdateTeamDispachOfRow(dr) == false)
                    {
                        return false;
                    }
                    if (Convert.IsDBNull(dr["TEAMDISPATCHID"]) == false && !string.IsNullOrWhiteSpace(dr["TEAMDISPATCHID"].ToString()))
                    {
                        string tableName = "CONTAINERTEAMDISPATCH";
                        if (UpdateTransferOfTable(tableName, "CONTAINERTEAMDISPATCHID", dr["TEAMDISPATCHID"]) == false) //更新批次班组派工表的结转标记
                        {
                            return false;
                        }
                    }
                }
            }
            if (tempDt5.Rows.Count > 0)//更新总表班组IDs信息
            {
                foreach (DataRow dr in tempDt5.Rows)
                {
                    UpdateConWorkcenterIdsAndTeamids(dr);
                }
            }

            #region 旧的
            //foreach (DataRow dr in containerData.Rows)
            //{
            //    if (Convert.ToInt64(dr["ISUSE"]) == 0) //批次班组派工信息更新
            //    {
            //    }
            //    else if (Convert.ToInt64(dr["ISUSE"]) == 1)//批次班组派工信息移除
            //    {
            //        string tableName = "CONTAINERTEAMDISPATCH";
            //        if (UpdateTransferOfTable(tableName, "CONTAINERTEAMDISPATCHID", dr["TEAMDISPATCHID"]) == false) //更新批次班组派工表的结转标记
            //        {
            //            return false;
            //        }

            //        dr["TEAMNAME"] = ""; dr["TEAMID"] = ""; dr["TEAMDISPATCHID"] = ""; dr["TEAMDISPATCHNUM"] = 0;
            //    }
            //    else
            //    {
            //        return false;
            //    }

            //    if (string.IsNullOrWhiteSpace(Convert.ToString(dr["WORKFLOWSTEPID"])) == false)//存在工序班组派工
            //    {

            //        if (Convert.ToString(dr["WORKFLOWSTEPID"]) != Convert.ToString(dr["CUWORKFLOWSTEPID"]))//判断是否是当前工序的班组派工
            //        {
            //            if (UpdateTransferOfTable("CONTAINERTEAMDISPATCH", "CONTAINERTEAMDISPATCHID", dr["TEAMDISPATCHID"]) == false) //更新批次班组派工表的结转标记
            //            {
            //                return false;
            //            }
            //            dr["TEAMNAME"] = ""; dr["TEAMID"] = ""; dr["TEAMDISPATCHID"] = ""; dr["TEAMDISPATCHNUM"] = 1;

            //        }
            //        else
            //        {
            //            if (UpdateTeamDispachOfRow(dr) == false)//更新的是当前工序的班组派工
            //            {
            //                return false;
            //            }
            //            if (Convert.IsDBNull(dr["TEAMDISPATCHID"]) == false && Convert.ToString(dr["TEAMDISPATCHID"]) != "")
            //            {
            //                string tableName = "CONTAINERTEAMDISPATCH";
            //                if (UpdateTransferOfTable(tableName, "CONTAINERTEAMDISPATCHID", dr["TEAMDISPATCHID"]) == false) //更新批次班组派工表的结转标记
            //                {
            //                    return false;
            //                }
            //            }

            //            return true;//存在当前工序直接跳出
            //        }

            //    }
            //    //else //批次班组派工
            //    //{
            //    if (UpdateTeamDispachOfRow(dr) == false)//更新的是批次班组派工或者TeamDispatchNum
            //        {
            //            return false;
            //        }
            //    //}

            //    if (Convert.IsDBNull ( dr["TEAMDISPATCHID"])== false  && Convert.ToString(dr["TEAMDISPATCHID"]) != "")
            //    {
            //        string tableName = "CONTAINERTEAMDISPATCH";
            //        if (UpdateTransferOfTable(tableName, "CONTAINERTEAMDISPATCHID", dr["TEAMDISPATCHID"]) == false) //更新批次班组派工表的结转标记
            //        {
            //            return false;
            //        }
            //    }

            //}
            #endregion
            return true;
        }
        #endregion

        #region 工区协作信息 creat:Wangjh
        /// <summary>
        /// 获取工区协作数据
        /// </summary>
        /// <param name="startDate"></param>
        /// <returns></returns>
        private DataTable GetWorkCenterDispachInfo()
        {
            //            string strSql = @"SELECT WC.WORKCENTERNAME,WC.WORKCENTERID,DECODE(CWDN.WORKCENTERDISPATCHNUM , NULL, 0, 1) WORKCENTERDISPATCHNUM,
            //                            CWD.CONTAINERWORKCENTERDISPATCHID WORKCENTERDISPATCHID,CWD.TOWORKCENTERID,C.CONTAINERID,CWD.ISUSE,CWD.ISTRANSFER  FROM CONTAINER C
            //                            LEFT JOIN CURRENTSTATUS CU ON CU.CURRENTSTATUSID=C.CURRENTSTATUSID
            //                            LEFT JOIN WORKFLOWSTEP WS ON WS.WORKFLOWSTEPID = CU.WORKFLOWSTEPID
            //                            LEFT JOIN WORKFLOW WF  ON WF.WORKFLOWID = WS.WORKFLOWID
            //                            LEFT JOIN WORKCENTER WC  ON WC.WORKCENTERID = C.WORKCENTERID
            //                            LEFT JOIN CONTAINERWORKCENTERDISPATCH CWD--工区协作
            //                            ON CWD.CONTAINERID = C.CONTAINERID AND CWD.WORKFLOWSTEPID = CU.WORKFLOWSTEPID
            //                            LEFT JOIN (SELECT COUNT(*) WORKCENTERDISPATCHNUM, CONTAINERID FROM CONTAINERWORKCENTERDISPATCH 
            //                            WHERE ISUSE = 0 AND RECVEMPLOYEEID IS NULL GROUP BY CONTAINERID) CWDN
            //                            ON CWDN.CONTAINERID = C.CONTAINERID
            //                            LEFT JOIN CDODEFINITION CDO ON CDO.CDODEFID = WF.CDOTYPEID
            //                            WHERE C.STATUS =1 AND C.PARENTCONTAINERID IS NULL AND C.TOGETHERFLAG <> ' ' AND C.QTY > 0 AND 
            //                            CDO.CDONAME = 'MachineMfgWorkFlow'  AND CWD.ISTRANSFER=0";
            string strSql = @"SELECT W.WORKCENTERNAME,CWD.WORKCENTERID,(CASE WHEN cwd.containerworkcenterdispatchid IS NOT NULL AND cwd.recvemployeeid IS NULL THEN 1 ELSE
                            0 END) WORKCENTERDISPATCHNUM,
                            CWD.CONTAINERWORKCENTERDISPATCHID WORKCENTERDISPATCHID,CWD.TOWORKCENTERID,C.CONTAINERID,CWD.ISUSE,CWD.ISTRANSFER,  
                            CWD.WORKFLOWSTEPID,C.WORKFLOWSTEPID AS CUWORKFLOWSTEPID,C.Workflowid cuWorkflowid,WS.SEQUENCE,CWD.RECVEMPLOYEEID,C.CONTAINERNAME,C.workflowstepsequence cusequence FROM CONTAINERWORKCENTERDISPATCH CWD--工区协作
                            INNER JOIN CONTAINERCURRENTINFO C ON CWD.CONTAINERID = C.CONTAINERID
                            LEFT JOIN WORKCENTER W ON W.WORKCENTERID=CWD.WORKCENTERID
                            LEFT JOIN WORKFLOWSTEP WS ON WS.WORKFLOWSTEPID=CWD.WORKFLOWSTEPID
                            WHERE CWD.ISTRANSFER=0	
                            ORDER BY WS.SEQUENCE";
            DataSet myDt = DatabaseHelper.Query(strSql);
            if (myDt == null || myDt.Tables.Count == 0)
            {
                return null;
            }
            return myDt.Tables[0];

        }
        /// <summary>
        /// 更新工区协作数据
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private Boolean UpdateWorkCenterDispachOfRow(DataRow dr)
        {
            string updateSql = @"UPDATE CONTAINERCURRENTINFO C SET WORKCENTERNAME=:WORKCENTERNAME,WORKCENTERID=:WORKCENTERID,
                                 WORKCENTERDISPATCHNUM=:WORKCENTERDISPATCHNUM,WORKCENTERDISPATCHID=:WORKCENTERDISPATCHID,
                                 TOWORKCENTERID=:TOWORKCENTERID
                                 WHERE C.CONTAINERID=:CONTAINERID";
            OracleParameter[] updateParam = new OracleParameter[6];
            updateParam[0] = DatabaseHelper.NewParameter(":WORKCENTERNAME", dr["WORKCENTERNAME"], OracleType.VarChar);
            updateParam[1] = DatabaseHelper.NewParameter(":WORKCENTERID", dr["WORKCENTERID"], OracleType.VarChar);
            updateParam[2] = DatabaseHelper.NewParameter(":WORKCENTERDISPATCHID", dr["WORKCENTERDISPATCHID"], OracleType.VarChar);
            updateParam[3] = DatabaseHelper.NewParameter(":CONTAINERID", dr["CONTAINERID"], OracleType.VarChar);


            updateParam[4] = DatabaseHelper.NewParameter(":TOWORKCENTERID", dr["TOWORKCENTERID"], OracleType.VarChar);

            updateParam[5] = DatabaseHelper.NewParameter(":WORKCENTERDISPATCHNUM", dr["WORKCENTERDISPATCHNUM"], OracleType.VarChar);
            int i = DatabaseHelper.ExecuteSql(updateSql, updateParam);
            InsertOracleLog(System.Reflection.MethodBase.GetCurrentMethod().Name, "更新工区协作信息", i, LogHelp.TranferSql(updateSql, updateParam), dr["CONTAINERNAME"].ToString());
            if (i > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 判断指定流水卡除指定工序外是否还有协作的工序,0:无协作的 1:协作未接收 2:全是协作已接收 3:部分协作已接收,还有协作未接收
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private int IsDispachStep(DataRow dr, ref string toWorkcenterID, ref string workcenterdispatchID)
        {
            string strSql = @"SELECT cwd.recvdate,cwd.workflowstepid,cwd.toworkcenterid,cwd.containerworkcenterdispatchid FROM containerworkcenterdispatch CWD
                              LEFT JOIN WORKFLOWSTEP WS ON WS.WORKFLOWSTEPID=CWD.WORKFLOWSTEPID
                              WHERE CWD.CONTAINERWORKCENTERDISPATCHID IS NOT NULL AND CWD.ISUSE=0";
            strSql += string.Format(" AND CWD.WORKCENTERID='{0}' AND CWD.CONTAINERID='{1}' AND WS.SEQUENCE<>{2} and ws.SEQUENCE>={3} and ws.workflowid='{4}'",
                dr["WORKCENTERID"], dr["CONTAINERID"], dr["SEQUENCE"], dr["cusequence"], dr["cuWorkflowid"]);
            strSql += " order by WS.SEQUENCE asc";
            DataSet myDs = DatabaseHelper.Query(strSql);
            DataRow[] drs = myDs.Tables[0].Select("recvdate is not null");
            if (myDs.Tables[0].Select("recvdate is not null and workflowstepid='" + dr["CUWORKFLOWSTEPID"].ToString() + "'").Length > 0)
            {
                workcenterdispatchID = drs[0]["containerworkcenterdispatchid"].ToString();
            }
            if (myDs.Tables[0].Rows.Count == 0)
            { return 0; }
            else
            {
                if (myDs.Tables[0].Select("recvdate is null").Length == myDs.Tables[0].Rows.Count)
                { return 1; }
                else if (drs.Length == myDs.Tables[0].Rows.Count)
                { toWorkcenterID = drs[0]["toworkcenterid"].ToString(); return 2; }
                else //if (drs.Length < myDs.Tables[0].Rows.Count)
                { toWorkcenterID = drs[0]["toworkcenterid"].ToString(); return 3; }
            }
        }

        /// <summary>
        /// 循环更新工区协作数据
        /// </summary>
        /// <param name="containerData"></param>
        /// <returns></returns>
        public Boolean UpdateWorkCenterDispach()
        {
            DataTable containerData = GetWorkCenterDispachInfo();
            foreach (DataRow dr in containerData.Rows)
            {
                string ID = dr["WORKCENTERDISPATCHID"].ToString();
                if (Convert.ToString(dr["CUWORKFLOWSTEPID"]) != Convert.ToString(dr["WORKFLOWSTEPID"])) //如果不是当前序
                {
                    dr["WORKCENTERDISPATCHID"] = "";
                    if (dr.IsNull("RECVEMPLOYEEID") == true)//如果不是当前工序并且未接收
                    {
                        dr["TOWORKCENTERID"] = "";
                    }
                }

                if (Convert.ToInt64(dr["ISUSE"]) == 1)//工区信息移除
                {
                    dr["WORKCENTERDISPATCHID"] = "";
                    dr["TOWORKCENTERID"] = "";
                    dr["WORKCENTERDISPATCHNUM"] = 0;
                }

                //其他序工区协作控制 0:无协作的 1:协作未接收 2:全是协作已接收 3:部分协作已接收,还有协作未接收
                string toworkcenterID = "";
                string workcenterdispatchID = "";
                int n = IsDispachStep(dr, ref toworkcenterID, ref workcenterdispatchID);
                if (n == 1)
                { dr["WORKCENTERDISPATCHNUM"] = 1; }
                else if (n == 2)
                { dr["TOWORKCENTERID"] = toworkcenterID; dr["WORKCENTERDISPATCHID"] = workcenterdispatchID; }
                else if (n == 3)
                { dr["WORKCENTERDISPATCHNUM"] = 1; dr["TOWORKCENTERID"] = toworkcenterID; dr["WORKCENTERDISPATCHID"] = workcenterdispatchID; }
                //
                UpdateWorkCenterDispachOfRow(dr);
                UpdateTransferOfTable("CONTAINERWORKCENTERDISPATCH", "CONTAINERWORKCENTERDISPATCHID", ID); //更新工区表的结转标记

            }
            return true;
        }
        #endregion

        #region 更新批次转工信息 creat:Wangjh
        /// <summary>
        /// 获取批次转工信息
        /// </summary>
        /// <param name="startDate"></param>
        /// <returns></returns>
        private DataTable GetContainerShipInfo()
        {
            //            string strSql = @"SELECT CSRT.CONTAINERSHIPRECORDID AS SHIPID,DECODE( CSR.SHIPNUM,NULL,0,1) SHIPNUM,
            //                              DECODE( CSR2.ISSHIP,NULL,0,1) ISSHIP,C.CONTAINERID,CSRT.ISTRANSFER,CSRT.ISUSE,CSRT.WORKFLOWSTEPID,
            //                              C.WORKFLOWSTEPID AS CUWORKFLOWSTEPID  FROM CONTAINERSHIPRECORD CSRT
            //                              INNER JOIN CONTAINERCURRENTINFO C ON CSRT.CONTAINERID = C.CONTAINERID 
            //                              LEFT JOIN (SELECT COUNT(CONTAINERSHIPRECORDID) SHIPNUM, CONTAINERID FROM CONTAINERSHIPRECORD
            //					                                WHERE ISUSE = 0 AND ProposerID IS NOT NULL AND TOACCEPTOR IS NULL --主制工厂申请，承制工厂未接收
            //					                                GROUP BY CONTAINERID) CSR ON CSR.CONTAINERID = C.CONTAINERID
            //                              LEFT JOIN (SELECT COUNT(CSRT2.CONTAINERSHIPRECORDID) ISSHIP,CSRT2.CONTAINERID FROM  CONTAINERSHIPRECORD CSRT2--主制工厂已申请但未转入
            //					                                LEFT JOIN CONTAINERSHIPRECIVE CSRE2 ON CSRT2.CONTAINERSHIPRECORDID=CSRE2.CONTAINERSHIPRECORDID
            //					                                WHERE CSRT2.ISUSE=0 AND CSRT2.PROPOSERID IS NOT NULL AND CSRE2.RECIVER IS NULL 
            //					                                GROUP BY CSRT2.CONTAINERID) CSR2 ON CSR2.CONTAINERID=C.CONTAINERID 
            //                              WHERE CSRT.ISTRANSFER=0";
            string strSql = @"SELECT NVL(CSRE.CONTAINERSHIPRECORDID,CSRT.CONTAINERSHIPRECORDID) AS SHIPID,NVL(CSRE.CONTAINERSHIPRECORDID,CSRT.CONTAINERSHIPRECORDID) AS CCISHIPID,C.SHIPNUM,C.SHIPNUM CCISHIPNUM,
                                (CASE WHEN (CSR2.ISSHIP IS NULL AND SWC.SUBWORKFLOWCHECKINFOID IS NULL) OR CSRT.ISUSE=1 OR C.SHIPNUM=8 THEN 0 ELSE 1 END) ISSHIP,C.CONTAINERID,CSRT.ISTRANSFER,CSRT.WORKFLOWSTEPID,
                                C.WORKFLOWSTEPID AS CUWORKFLOWSTEPID,CSRT.ISUSE CSRTISUSE,CSRE.ISUSE CSREISUSE,CSRT.PROPOSERID,CSRT.PREPOSERDATE,
                                CSRT.AUDITOR,CSRT.AUDITDATE,CSRT.AUDITRESULT,CSRT.SENDER,CSRT.TOACCEPTOR,CSRT.TOWORKCENTERID,NVL(CSRQ.SUMCompleteQty,0) SUMCompleteQty,
                                C.QTY,CSRE.RECIVER,DECODE(CSRT.SENDER,NULL, C.ORIGINALFACTORYID,CSRT.TOFACTORYID) FACTORYID,
                                FA.FACTORYNAME,DECODE(CSRT.TOWORKCENTERID,NULL,C.WORKCENTERID,CSRT.TOWORKCENTERID) WORKCENTERID,
                                WC.WORKCENTERNAME,CSRT.TOWORKFLOWSTEPID,CSRE.EMPLOYEEID AS COMPLETEID,CSRE.ISTRANSFER AS CSREISTRANSFER,
                                C.ORIGINALFACTORYID,FA2.FACTORYNAME AS ORIGINALFACTORYNAME,C.FROMWORKCENTERID,WC2.WORKCENTERNAME AS FROMWORKCENTERNAME, 
                                NVL2(SWC.SUBWORKFLOWCHECKINFOID,1,0) ISsubworkflow,(CASE WHEN ws.islaststep=1 OR WS.DEFAULTPATHID IS NULL THEN 1 ELSE 0  END) cuislaststep,
                                cuw.factoryid cuworkflowfactoryid,C.CONTAINERNAME FROM CONTAINERSHIPRECORD CSRT 
                                LEFT JOIN CONTAINERCURRENTINFO C ON CSRT.CONTAINERID = C.CONTAINERID
                                LEFT JOIN Workflowstep ws ON ws.workflowstepid=c.workflowstepid

                                 LEFT JOIN (
								SELECT swc.containerid,swc.subworkflowid,max(swc.createdate) MAXcreatedate FROM subworkflowcheckinfo swc
									        GROUP BY swc.containerid,swc.subworkflowid
						        ) a ON a.containerid=c.containerid AND a.subworkflowid=c.workflowid 
                                LEFT JOIN SUBWORKFLOWCHECKINFO SWC ON SWC.CONTAINERID=c.CONTAINERID AND SWC.SUBWORKFLOWID=c.WORKFLOWID and swc.createdate=a.MAXcreatedate--关联子工艺校对表

                                LEFT JOIN CONTAINERSHIPRECIVE CSRE ON CSRE.CONTAINERSHIPRECORDID=CSRT.CONTAINERSHIPRECORDID AND csre.containerid=c.containerid 
                                LEFT JOIN (SELECT COUNT(CSRT2.CONTAINERSHIPRECORDID) ISSHIP,CSRT2.CONTAINERID,CSRSS.WORKFLOWSTEPID FROM  CONTAINERSHIPRECORD CSRT2--主制工厂已申请但未转入
                                            LEFT JOIN CONTAINERSHIPRECIVE CSRE2 ON CSRT2.CONTAINERSHIPRECORDID=CSRE2.CONTAINERSHIPRECORDID
                                            LEFT JOIN CONTAINERSHIPRECORDSTEP CSRSS ON CSRSS.CONTAINERSHIPRECORDID=CSRT2.CONTAINERSHIPRECORDID
                                            WHERE CSRT2.ISUSE=0 AND (CSRT2.PROPOSERID IS NOT NULL AND CSRT2.Auditresult IS NULL) OR (CSRT2.Auditresult=0 AND CSRE2.RECIVER IS NULL )

                                            GROUP BY CSRT2.CONTAINERID,CSRSS.WORKFLOWSTEPID) CSR2 ON CSR2.CONTAINERID=C.CONTAINERID  AND CSR2.WORKFLOWSTEPID=C.WORKFLOWSTEPID 
					
                                LEFT JOIN (SELECT NVL(SUM(CSRE.COMPLETEQTY) ,0) SUMCompleteQty,CSRE.CONTAINERSHIPRECORDID,csre.containerid
					                        FROM CONTAINERSHIPRECIVE CSRE GROUP BY CSRE.CONTAINERSHIPRECORDID,csre.containerid ) CSRQ ON
										    CSRQ.CONTAINERSHIPRECORDID=CSRT.CONTAINERSHIPRECORDID AND csrq.containerid=c.containerid 					
	                       	    LEFT JOIN FACTORY FA ON FA.FACTORYID=DECODE(CSRT.SENDER,NULL, C.ORIGINALFACTORYID,CSRT.TOFACTORYID)	
                                LEFT JOIN WORKCENTER WC ON WC.WORKCENTERID=	DECODE(CSRT.TOWORKCENTERID,NULL,C.WORKCENTERID,CSRT.TOWORKCENTERID)	
                                LEFT JOIN FACTORY FA2 ON FA2.FACTORYID=C.ORIGINALFACTORYID
                                LEFT JOIN WORKCENTER WC2 ON WC2.WORKCENTERID=C.FROMWORKCENTERID		
                                LEFT JOIN workflowstep fws ON fws.workflowstepid=csrt.workflowstepid--转工申请的开始工序
                                LEFT JOIN Workflow cuw ON cuw.workflowid=c.workflowid--当前工艺  							
                                WHERE C.containerstatus=1 AND C.workflowstepid IS NOT NULL AND C.CONTAINERID IS NOT NULL AND (CSRT.ISTRANSFER=0 OR (CSRT.ISTRANSFER=1 AND CSRE.ISTRANSFER=0) OR (C.WORKFLOWSTEPID=CSRT.TOWORKFLOWSTEPID AND (csrt.senddate IS not NULL OR C.SHIPNUM=2) AND csrt.isuse=0)) --或者已加工到当前工序
                                 ORDER BY C.CONTAINERNAME,fws.sequence ASC ";
            DataTable dt1 = DatabaseHelper.Query_ReturnDatTable(strSql);
            //分批出来的卡，只可能有完成或转入记录
            strSql = @"
                    SELECT csre.containerid,cci.originalfactoryid,fa.factoryname AS ORIGINALFACTORYNAME,cci.fromworkcenterid,cci.fromworkcentername,csrq.SUMCompleteQty,cci.qty,CSRE.EMPLOYEEID AS COMPLETEID
                    ,csre.reciver,csre.recivedate,csre.containershiprecordid shipid,csre.containershiprecordid CCIshipid,csre.isuse csrtisuse,(CASE WHEN csre.isuse=1 OR cci.shipnum=8 THEN 0 ELSE 1 END) isship,CCI.CONTAINERNAME FROM containercurrentinfo cci
                    LEFT JOIN (
		                    SELECT NVL(SUM(CSRE.COMPLETEQTY) ,0) SUMCompleteQty,CSRE.Containerid
		                    FROM CONTAINERSHIPRECIVE CSRE GROUP BY CSRE.Containerid
                             ) CSRQ ON csrq.containerid=cci.containerid
                    LEFT JOIN containershiprecive csre ON csre.containerid=cci.containerid
                    LEFT JOIN CONTAINERSHIPRECORD CSR ON CSR.CONTAINERSHIPRECORDID=CSRE.CONTAINERSHIPRECORDID AND CSR.CONTAINERID=CSRE.CONTAINERID
                    LEFT JOIN factory fa ON fa.factoryid=cci.originalfactoryid
                    WHERE  CCI.workflowstepid IS NOT NULL AND csre.istransfer=0 AND CSR.CONTAINERSHIPRECORDID IS NULL
                      ";
            DataTable dt2 = DatabaseHelper.Query_ReturnDatTable(strSql);
            //
            dt1.Merge(dt2);
            return dt1;
        }
        /// <summary>
        /// 更新批次转工信息
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private Boolean UpdateContainerShipOfRow(DataRow dr)
        {
            string updateSql = @"UPDATE CONTAINERCURRENTINFO C SET SHIPNUM=:SHIPNUM,ISSHIP=:ISSHIP,SHIPID=:SHIPID,FACTORYID=:FACTORYID, 
                                FACTORYNAME=:FACTORYNAME,WORKCENTERID=:WORKCENTERID,WORKCENTERNAME=:WORKCENTERNAME ";

            OracleParameter[] updateParam = new OracleParameter[8];
            updateParam[0] = DatabaseHelper.NewParameter(":CONTAINERID", dr["CONTAINERID"], OracleType.VarChar);

            if (Convert.IsDBNull(dr["CSRTISUSE"]) == false && Convert.ToInt16(dr["CSRTISUSE"]) == 0 && Convert.IsDBNull(dr["PREPOSERDATE"]) == false)
            {
                if (Convert.IsDBNull(dr["AUDITOR"])) //dr["AUDITOR"]=""
                {
                    dr["SHIPNUM"] = 1;//已申请待审核
                }
                if (Convert.IsDBNull(dr["auditdate"]) == false && Convert.IsDBNull(dr["SENDER"]))
                {
                    dr["SHIPNUM"] = 2;//已审核
                    if (Convert.ToInt16(dr["AUDITRESULT"]) == 1)
                    {
                        //string tableName = "CONTAINERSHIPRECORD";
                        //string ID = "CONTAINERSHIPRECORDID";
                        //object IDValue = dr["SHIPID"];
                        //if (UpdateTransferOfTable(tableName, ID, IDValue) == false) //更新转工表的结转标记
                        //{
                        //    return false;
                        //}
                        dr["ShipNum"] = 0;
                        dr["ShipID"] = "";
                        dr["IsShip"] = 0;
                    }
                }
                if (Convert.IsDBNull(dr["SENDER"]) && (!Convert.IsDBNull(dr["AUDITRESULT"])) && Convert.ToInt16(dr["AUDITRESULT"]) == 0)
                {
                    if (Convert.ToString(dr["WORKFLOWSTEPID"]) == Convert.ToString(dr["CUWORKFLOWSTEPID"]))//当前工序
                    {
                        dr["SHIPNUM"] = 3;//待转出 需当前工序
                    }
                    if (Convert.ToInt32(dr["ISsubworkflow"]) == 1 && dr["ORIGINALFACTORYID"] != dr["cuworkflowfactoryid"]) //是子工艺,且子工艺作为一道序转工
                    {
                        dr["SHIPNUM"] = 3;//待转出 
                    }

                }
                if (Convert.IsDBNull(dr["SENDER"]) == false && Convert.IsDBNull(dr["TOACCEPTOR"]) && Convert.IsDBNull(dr["ToWorkCenterID"]))
                {
                    dr["SHIPNUM"] = 4;//已转出待接收
                }
                if (Convert.IsDBNull(dr["RECIVER"]) == false)//转回 Convert.IsDBNull(dr["COMPLETEID"]) == true &&
                {
                    //if (ShipBackUpdate(dr) == false)
                    //{
                    //    return false;
                    //}
                    //
                    dr["FACTORYID"] = dr["ORIGINALFACTORYID"];
                    dr["FACTORYNAME"] = dr["ORIGINALFACTORYNAME"];
                    dr["WORKCENTERID"] = dr["FROMWORKCENTERID"];
                    dr["WORKCENTERNAME"] = dr["FROMWORKCENTERNAME"];
                    dr["SHIPID"] = "";
                    dr["SHIPNUM"] = 8;//已转入
                    dr["ISSHIP"] = 0;
                }
                else if (Convert.IsDBNull(dr["TOACCEPTOR"]) == false && Convert.IsDBNull(dr["ToWorkCenterID"]) == false)//接收后
                {
                    if (Convert.ToInt64(dr["SUMCompleteQty"]) < Convert.ToInt64(dr["QTY"]))
                    {
                        dr["SHIPNUM"] = 5;//已接收
                        if (Convert.IsDBNull(dr["COMPLETEID"]) && Convert.ToString(dr["CUWORKFLOWSTEPID"]) == Convert.ToString(dr["TOWORKFLOWSTEPID"]))//转工完成人为空且当前工序和转工的最后一道相同
                        {
                            dr["SHIPNUM"] = 6;//待完成  
                        }
                        if (Convert.IsDBNull(dr["COMPLETEID"]) && Convert.ToInt32(dr["ISsubworkflow"]) == 1 && Convert.ToInt32(dr["cuislaststep"]) == 1)//转工完成人为空，为子工艺，且子工艺已经干完
                        {
                            dr["SHIPNUM"] = 6;//待完成  
                        }
                        if (Convert.ToInt64(dr["SHIPNUM"]) == 5) //当承制工厂接收后清除原来的班组信息 2017-6-23
                        {
                            updateSql += " ,TEAMNAME='',TEAMID='',TEAMDISPATCHID='',TEAMDISPATCHNUM=0";
                        }
                    }
                    if (Convert.ToInt64(dr["SUMCompleteQty"]) >= Convert.ToInt64(dr["QTY"]))
                    {
                        //if (Convert.ToString(dr["CUWORKFLOWSTEPID"]) == Convert.ToString(dr["TOWORKFLOWSTEPID"])) //当前工序和转工的最后一道相同
                        // {
                        if (Convert.IsDBNull(dr["COMPLETEID"]) == false && Convert.IsDBNull(dr["RECIVER"]))
                        {
                            dr["SHIPNUM"] = 7;//已完成未转入
                        }
                        //}
                        if (Convert.ToInt32(dr["ISsubworkflow"]) == 1 && Convert.ToInt32(dr["cuislaststep"]) == 1)//转工完成人为空，为子工艺，且子工艺已经干完
                        {
                            if (Convert.IsDBNull(dr["COMPLETEID"]) == false && Convert.IsDBNull(dr["RECIVER"]))
                            {
                                dr["SHIPNUM"] = 7;//已完成未转入
                            }
                        }
                    }

                }
            }
            else //处理分批出来的只有完成记录和转回记录的情况
            {
                if (Convert.ToInt64(dr["SUMCompleteQty"]) >= Convert.ToInt64(dr["QTY"]))
                {
                    //if (Convert.ToString(dr["CUWORKFLOWSTEPID"]) == Convert.ToString(dr["TOWORKFLOWSTEPID"])) //当前工序和转工的最后一道相同
                    // {
                    if (Convert.IsDBNull(dr["COMPLETEID"]) == false && Convert.IsDBNull(dr["RECIVER"]))
                    {
                        dr["SHIPNUM"] = 7;//已完成未转入
                    }
                    //}

                }
                if (Convert.IsDBNull(dr["COMPLETEID"]) == false && Convert.IsDBNull(dr["RECIVER"]) == false)
                {
                    dr["FACTORYID"] = dr["ORIGINALFACTORYID"];
                    dr["FACTORYNAME"] = dr["ORIGINALFACTORYNAME"];
                    dr["WORKCENTERID"] = dr["FROMWORKCENTERID"];
                    dr["WORKCENTERNAME"] = dr["FROMWORKCENTERNAME"];
                    dr["SHIPID"] = "";
                    dr["SHIPNUM"] = 8;//已转入
                    dr["ISSHIP"] = 0;//已转入
                }
                // UpdateTransferOfTable("CONTAINERSHIPRECIVE", "ContainerID", dr["containerid"]); //更新转工接收表的结转标记
            }
            //规避掉可能出现的isship字段值错误
            if (dr.IsNull("SHIPNUM") || int.Parse(dr["SHIPNUM"].ToString()) == 8)
            { dr["SHIPNUM"] = 0; dr["ISSHIP"] = 0; }
            if (int.Parse(dr["ISSHIP"].ToString()) == 0 && int.Parse(dr["SHIPNUM"].ToString()) < 8 && int.Parse(dr["SHIPNUM"].ToString()) > 0)
                dr["ISSHIP"] = 1;
            //
            if (dr["SHIPNUM"].ToString() == dr["CCISHIPNUM"].ToString())
                return true;
            updateSql += " WHERE C.CONTAINERID=:CONTAINERID";
            updateParam[1] = DatabaseHelper.NewParameter(":SHIPID", dr["SHIPID"], OracleType.VarChar);
            updateParam[2] = DatabaseHelper.NewParameter(":SHIPNUM", dr["SHIPNUM"], OracleType.Number);
            updateParam[3] = DatabaseHelper.NewParameter(":ISSHIP", dr["ISSHIP"], OracleType.Number);
            updateParam[4] = DatabaseHelper.NewParameter(":FACTORYID", dr["FACTORYID"], OracleType.VarChar);
            updateParam[5] = DatabaseHelper.NewParameter(":FACTORYNAME", dr["FACTORYNAME"], OracleType.VarChar);
            updateParam[6] = DatabaseHelper.NewParameter(":WORKCENTERID", dr["WORKCENTERID"], OracleType.VarChar);
            updateParam[7] = DatabaseHelper.NewParameter(":WORKCENTERNAME", dr["WORKCENTERNAME"], OracleType.VarChar);
            int i = DatabaseHelper.ExecuteSql(updateSql, updateParam);
            #region 更新总表记录
            //string temSql = string.Format(@"SELECT REPLACE( il.xml,'''','') xml FROM interface_log il WHERE  to_char(il.createdate,'yyyy/mm/dd')  =to_char( SYSDATE,'yyyy/mm/dd') and il.logmessage like '%更新转工信息%' and il.product='{0}'", dr["ContainerName"]);
            //DataTable temDt = DatabaseHelper.Query_ReturnDatTable(temSql);
            string sql = LogHelp.TranferSql(updateSql, updateParam);
            //if (temDt .Select ("xml='"+sql.Replace ("'","")+"'").Length ==0)
            InsertOracleLog(System.Reflection.MethodBase.GetCurrentMethod().Name, "更新转工信息", i, sql, dr["CONTAINERNAME"].ToString());
            #endregion
            if (i > 0)
            {
                return true;
            }
            else
            {
                return false;
            }

        }
        /// <summary>
        /// 循环更新批次转工信息
        /// </summary>
        /// <param name="containerData"></param>
        /// <returns></returns>
        public Boolean UpdateContainerShip()
        {

            DataTable containerData = GetContainerShipInfo();

            List<string> contianerLi = new List<string>();
            DataRow[] drs1 = containerData.Select("ISTRANSFER=0 or CSREISTRANSFER=0");
            DataRow[] drs2 = containerData.Select("(ISTRANSFER<>0 OR ISTRANSFER IS NULL) and (CSREISTRANSFER<>0 OR CSREISTRANSFER IS NULL)");

            //DataTable temDt=new DataTable() ;
            //foreach (DataRow dr in drs2)
            //{
            //    temDt.ImportRow(dr);
            //}

            LoopContainerShipData(drs1, contianerLi);
            LoopContainerShipData(drs2, contianerLi);
            return true;
        }

        /// <summary>
        /// 转回时更新
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        Boolean ShipBackUpdate(DataRow dr)
        {

            string tableName = "CONTAINERSHIPRECORD";
            string ID = "CONTAINERSHIPRECORDID";
            object IDValue = dr["SHIPID"];

            UpdateTransferOfTable(tableName, ID, IDValue);//更新转工表的结转标记

            if (Convert.ToString(dr["CSREISTRANSFER"]) == "0")
            {
                UpdateTransferOfTable("CONTAINERSHIPRECIVE", ID, IDValue);//更新转工接收表的结转标记
            }
            dr["FACTORYID"] = dr["ORIGINALFACTORYID"];
            dr["FACTORYNAME"] = dr["ORIGINALFACTORYNAME"];
            dr["WORKCENTERID"] = dr["FROMWORKCENTERID"];
            dr["WORKCENTERNAME"] = dr["FROMWORKCENTERNAME"];
            dr["SHIPID"] = "";
            dr["SHIPNUM"] = 8;//已转入
            dr["ISSHIP"] = 0;

            return true;
        }

        /// <summary>
        /// 循环处理数据
        /// </summary>
        /// <param name="drs"></param>
        void LoopContainerShipData(DataRow[] drs, List<string> contianerLi)
        {
            foreach (DataRow dr in drs)
            {
                if (contianerLi.Contains(dr["containerid"].ToString()))
                    continue;
                else
                    contianerLi.Add(dr["containerid"].ToString());
                if (Convert.IsDBNull(dr["CSRTISUSE"]) == false && Convert.ToInt64(dr["CSRTISUSE"]) == 1)//转工信息移除
                {
                    //string tableName = "CONTAINERSHIPRECORD";
                    //string ID = "CONTAINERSHIPRECORDID";
                    //object IDValue = dr["SHIPID"];
                    //UpdateTransferOfTable(tableName, ID, IDValue); //更新转工表的结转标记

                    //自动转工撤回或者删除时还原相关字段
                    dr["SHIPID"] = "";
                    dr["SHIPNUM"] = 0;
                    dr["FACTORYID"] = dr["ORIGINALFACTORYID"];
                    dr["FACTORYNAME"] = dr["ORIGINALFACTORYNAME"];
                    dr["WORKCENTERID"] = dr["FROMWORKCENTERID"];
                    dr["WORKCENTERNAME"] = dr["FROMWORKCENTERNAME"];
                }

                if (UpdateContainerShipOfRow(dr) == false)
                {
                    continue;
                }
                if (Convert.IsDBNull(dr["CCISHIPID"]) == false && Convert.ToString(dr["CCISHIPID"]) != "")
                {
                    string tableName = "CONTAINERSHIPRECORD";
                    string ID = "CONTAINERSHIPRECORDID";
                    object IDValue = dr["CCISHIPID"];
                    // UpdateTransferOfTable(tableName, ID, IDValue);  //更新转工表的结转标记
                    if (dr["ISTRANSFER"].ToString() == "0")
                    {
                        UpdateTransferOfTable(tableName, ID, IDValue); //更新转工接收表的结转标记
                    }
                    if (Convert.ToString(dr["CSREISTRANSFER"]) == "0")
                    {
                        UpdateTransferOfTable("CONTAINERSHIPRECIVE", ID, IDValue); //更新转工接收表的结转标记

                    }

                }
            }

        }
        #endregion

        #region 将检验表中的数据写入生产工时表 create tianFW 循环处理改为1分钟sync*60处理一次，处理数据在检验生成一分钟之后处理，防止报废数没有写入报工记录
        /// <summary>
        /// 添加生产工时信息
        /// </summary>
        /// <param name="containercheckid"></param>
        private void AddContainerStepTimeSheetInfo(DataRow dr, Int32 splitcount)
        {
            StringBuilder sb = new StringBuilder();//CONTAINERSTEPWORKREPORTID
            sb.AppendLine("INSERT INTO CONTAINERSTEPTIMESHEET(CONTAINERID,FACTORYID,WORKCENTERID,TEAMID,WORKFLOWSTEPID,WORKERID,CHECKERID,QTY,SCRAPQTY,CONTAINERCHECKINFOID,");
            sb.AppendLine("CONTAINERSTEPTIMESHEETID,CREATEDATE,ISUSE,CONTAINERNAME,WORKFLOWSTEPNAME,CONTAINERSTEPWORKREPORTID,splitcount,Stepinfoid,CHECKDATE,checktype,machineno,bigworkflowstepid,bigworkflowstepname)");
            sb.AppendLine("VALUES(:CONTAINERID,:FACTORYID,:WORKCENTERID,:TEAMID,:WORKFLOWSTEPID,:WORKERID,:CHECKERID,:QTY,:SCRAPQTY,:CONTAINERCHECKINFOID,");
            sb.AppendLine(":CONTAINERSTEPTIMESHEETID,:CREATEDATE,0,:CONTAINERNAME,:WORKFLOWSTEPNAME,:CONTAINERSTEPWORKREPORTID,:splitcount,:Stepinfoid,:CHECKDATE,:checktype,:machineno,:bigworkflowstepid,:bigworkflowstepname)");
            OracleParameter[] insertpara = new OracleParameter[22];

            insertpara[0] = new OracleParameter(":CONTAINERID", OracleType.VarChar);
            insertpara[0].Direction = ParameterDirection.Input;
            insertpara[0].Value = Convert.ToString(dr["CONTAINERID"]);

            insertpara[1] = new OracleParameter(":FACTORYID", OracleType.VarChar);
            insertpara[1].Direction = ParameterDirection.Input;
            if (Convert.ToString(dr["FACTORYID"]) == "")//工序检报工信息没有分厂信息，则取检验员的分厂信息
            {
                insertpara[1].Value = dr["CCIFACTORYID"];
            }
            else
            {
                insertpara[1].Value = dr["FACTORYID"];
            }

            insertpara[2] = new OracleParameter(":WORKCENTERID", OracleType.VarChar);
            insertpara[2].Direction = ParameterDirection.Input;
            if (Convert.ToString(dr["WORKCENTERID"]) == "")//工序检报工信息没有工区信息，则为空 班组相同处理
            {
                insertpara[2].Value = DBNull.Value;
            }
            else
            {
                insertpara[2].Value = dr["WORKCENTERID"];
            }

            insertpara[3] = new OracleParameter(":TEAMID", OracleType.VarChar);
            insertpara[3].Direction = ParameterDirection.Input;
            if (Convert.ToString(dr["TEAMID"]) == "")
            {
                insertpara[3].Value = DBNull.Value;
            }
            else
            {
                insertpara[3].Value = dr["TEAMID"];
            }

            insertpara[4] = new OracleParameter(":WORKFLOWSTEPID", OracleType.VarChar);
            insertpara[4].Direction = ParameterDirection.Input;
            insertpara[4].Value = Convert.ToString(dr["WORKFLOWSTEPID"]);

            insertpara[5] = new OracleParameter(":WORKERID", OracleType.VarChar);
            insertpara[5].Direction = ParameterDirection.Input;
            if (Convert.ToString(dr["WORKERID"]) == "")
            {
                insertpara[5].Value = dr["CHECKERID"];//检验序没有报工人信息，取检验员信息
            }
            else
            {
                insertpara[5].Value = dr["WORKERID"];
            }

            insertpara[6] = new OracleParameter(":CHECKERID", OracleType.VarChar);
            insertpara[6].Direction = ParameterDirection.Input;
            insertpara[6].Value = Convert.ToString(dr["CHECKERID"]);

            insertpara[7] = new OracleParameter(":QTY", OracleType.Number);
            insertpara[7].Direction = ParameterDirection.Input;
            insertpara[7].Value = Convert.ToInt32(dr["REPORTQTY"]);

            insertpara[8] = new OracleParameter(":SCRAPQTY", OracleType.Number);
            insertpara[8].Direction = ParameterDirection.Input;
            insertpara[8].Value = Convert.ToInt32(dr["LOSSQTY"]);

            insertpara[9] = new OracleParameter(":CONTAINERCHECKINFOID", OracleType.VarChar);
            insertpara[9].Direction = ParameterDirection.Input;
            insertpara[9].Value = dr["GODID"];

            String ID = Convert.ToString(System.Guid.NewGuid());
            insertpara[10] = new OracleParameter(":CONTAINERSTEPTIMESHEETID", OracleType.VarChar);
            insertpara[10].Direction = ParameterDirection.Input;
            insertpara[10].Value = ID;

            insertpara[11] = new OracleParameter(":CREATEDATE", OracleType.DateTime);
            insertpara[11].Direction = ParameterDirection.Input;
            insertpara[11].Value = Convert.ToString(dr["CREATEDATE"]);

            insertpara[12] = new OracleParameter(":CONTAINERNAME", OracleType.VarChar);
            insertpara[12].Direction = ParameterDirection.Input;
            insertpara[12].Value = Convert.ToString(dr["CONTAINERNAME"]);

            insertpara[13] = new OracleParameter(":WORKFLOWSTEPNAME", OracleType.VarChar);
            insertpara[13].Direction = ParameterDirection.Input;
            insertpara[13].Value = Convert.ToString(dr["WORKFLOWSTEPNAME"]);

            insertpara[14] = new OracleParameter(":CONTAINERSTEPWORKREPORTID", OracleType.VarChar);
            insertpara[14].Direction = ParameterDirection.Input;
            insertpara[14].Value = Convert.ToString(dr["CONTAINERSTEPWORKREPORTID"]);

            insertpara[15] = new OracleParameter(":splitcount", OracleType.Number);
            insertpara[15].Direction = ParameterDirection.Input;
            insertpara[15].Value = splitcount;

            insertpara[16] = new OracleParameter(":Stepinfoid", OracleType.VarChar);
            insertpara[16].Direction = ParameterDirection.Input;
            if (dr.IsNull("Stepinfoid"))
            {
                insertpara[16].Value = DBNull.Value;
            }
            else
            {
                insertpara[16].Value = dr["Stepinfoid"].ToString();
            }

            insertpara[17] = new OracleParameter(":CHECKDATE", OracleType.DateTime);
            insertpara[17].Direction = ParameterDirection.Input;
            insertpara[17].Value = Convert.ToString(dr["CHECKDATE"].ToString());

            insertpara[18] = new OracleParameter(":checktype", OracleType.VarChar);
            insertpara[18].Direction = ParameterDirection.Input;
            insertpara[18].Value = Convert.ToString(dr["checktype"]);
            //总体专用 发动机号
            insertpara[19] = new OracleParameter(":machineno", OracleType.VarChar);
            insertpara[19].Direction = ParameterDirection.Input;
            insertpara[19].Value = Convert.ToString(dr["machineno"]);
            //总体专用 大阶段id
            insertpara[20] = new OracleParameter(":bigworkflowstepid", OracleType.VarChar);
            insertpara[20].Direction = ParameterDirection.Input;
            insertpara[20].Value = Convert.ToString(dr["bigworkflowstepid"]);
            //总体专用 大阶段名称
            insertpara[21] = new OracleParameter(":bigworkflowstepname", OracleType.VarChar);
            insertpara[21].Direction = ParameterDirection.Input;
            insertpara[21].Value = Convert.ToString(dr["bigworkflowstepname"]);
            int i = DatabaseHelper.ExecuteSql(Convert.ToString(sb), insertpara);
            InsertOracleLog(System.Reflection.MethodBase.GetCurrentMethod().Name, "插入生产工时", i, LogHelp.TranferSql(sb.ToString(), insertpara), dr["CONTAINERNAME"].ToString());//add:Wangjh 20180530 日志记录
        }

        /// <summary>
        /// 将检验表对应的报工信息一一对应添加到工时表 create tianFW 2017年11月7日
        /// </summary>
        public void GetStepCheckWorkReportToTimeSheet()
        {
            String strsql = @"SELECT CSD.CONTAINERSTEPDISPATCHID,CSW.CONTAINERID,C.CONTAINERNAME,CSW.WORKFLOWSTEPID,WS.WORKFLOWSTEPNAME,CSW.WORKCENTERID,
                            CSW.TEAMID,C.CONTAINERTYPE,CSW.CONTAINERSTEPWORKREPORTID,CSW.QTY + NVL(csw.specimenqty,0) REPORTQTY,CSW.FACTORYID,CCI.FACTORYID CCIFACTORYID,
                            CSW.WORKERID,NVL(CSW.LOSSQTY,0) LOSSQTY,CCI.CONTAINERCHECKINFOID GODID,CCI.CHECKERID,CSW.CREATEDATE,C.CONTAINERNAME,csw.stepinfoid,CCI.CREATEDATE CHECKDATE,
                            u.attributevalue FACTORYCODE,csw.checktype,ep.machineno,ep.workflowstepid bigworkflowstepid,ep.workflowstepname bigworkflowstepname
                            FROM CONTAINERCHECKINFO CCI
                            LEFT JOIN CONTAINERSTEPWORKREPORT CSW ON CCI.CONTAINERSTEPWORKREPORTID = CSW.CONTAINERSTEPWORKREPORTID
                            LEFT JOIN CONTAINERSTEPDISPATCH CSD ON CSD.CONTAINERSTEPDISPATCHID = CSW.CONTAINERSTEPDISPATCHID
                            LEFT JOIN CONTAINERSTEPTIMESHEET CTS ON CTS.CONTAINERCHECKINFOID = CCI.CONTAINERCHECKINFOID
                            LEFT JOIN CONTAINERSTEPTIMESHEET CTS_ ON CTS_.CONTAINERSTEPWORKREPORTID = CCI.CONTAINERSTEPWORKREPORTID
                            LEFT JOIN CONTAINER C ON C.CONTAINERID = CSW.CONTAINERID
                            LEFT JOIN WORKFLOWSTEP WS ON WS.WORKFLOWSTEPID = CSW.WORKFLOWSTEPID 
                            left join enginepartplan ep on ep.concontainerid=csw.containerid  
                            LEFT JOIN userattribute u ON u.parentid= CSW.FACTORYID AND u.userattributename='分厂代码'                             
                            WHERE cci.createdate>=sysdate-1/24 and  nvl(CTS.CONTAINERSTEPTIMESHEETID,'0')='0' 
                            AND nvl(CTS_.CONTAINERSTEPTIMESHEETID,'0')='0'
                            AND CCI.ISUSE=0 AND CSW.ISUSE=0 AND NVL(CSD.ISUSE,0)=0";
            DataTable dt = DatabaseHelper.Query_ReturnDatTable(strsql);
            //Modify by Yuxj20181031 增加去重
            dt = dt.DefaultView.ToTable(true);
            if (dt.Rows.Count == 0)
            {
                return;
            }
            DataTable newdt = dt.DefaultView.ToTable(true, "FACTORYID");
            newdt.Columns.Add("DJDKDRPG");
            foreach (DataRow dr in newdt.Rows)
            {
                dr["DJDKDRPG"] = GetFactoryAttributes(dr["FACTORYID"].ToString(), "单件多人派工工时平均分配");
            }
            String strValue = "";
            foreach (DataRow r in dt.Rows)
            {
                foreach (DataRow dr in newdt.Rows)
                {
                    if (dr["FACTORYID"].ToString() == r["FACTORYID"].ToString())
                    {
                        strValue = dr["DJDKDRPG"].ToString();
                        break;
                    }
                }
                if (strValue == "是" && Convert.ToString(r["CONTAINERTYPE"]) == "7")//如果是单件单卡多人派工并且是单件单卡检验
                {
                    if (!r.IsNull("CONTAINERSTEPDISPATCHID"))
                    {
                        DataTable dt_ = GetDispatchWorkers(r["CONTAINERSTEPDISPATCHID"].ToString());
                        if (r["FACTORYCODE"].ToString() == "603")
                        {
                            dt_ = GetZSDispatchWorkers(r["CONTAINERSTEPDISPATCHID"].ToString());
                        }

                        if (dt_.Rows.Count > 0)//如果派工给多人，则分报工数量存储工时
                        {
                            foreach (DataRow dr in dt_.Rows)
                            {
                                r["WORKERID"] = dr["WORKERID"].ToString();
                                AddContainerStepTimeSheetInfo(r, dt_.Rows.Count);
                            }
                            continue;
                        }

                    }

                }

                AddContainerStepTimeSheetInfo(r, 1);

            }
        }

        /// <summary>
        /// 将成品检验表对应的报工信息一一对应添加到工时表 create tianFW 2017年11月7日
        /// 
        /// </summary>
        public void GetFinishCheckWorkReportToTimeSheet()
        {
            String strsql = @"SELECT CSD.CONTAINERSTEPDISPATCHID,CSW.CONTAINERID,C.CONTAINERNAME,CSW.WORKFLOWSTEPID,WS.WORKFLOWSTEPNAME,
CSW.WORKCENTERID,CSW.TEAMID,CSW.FACTORYID,CFCI.FACTORYID CCIFACTORYID,csw.stepinfoid,CSW.CONTAINERSTEPWORKREPORTID,
CSW.WORKERID,NVL(CSW.LOSSQTY,0) LOSSQTY,CFCI.CONTAINERFINISHEDCHECKINFOID GODID,CFCI.CHECKERID,CSW.QTY + NVL(csw.specimenqty,0) REPORTQTY,
C.CONTAINERTYPE,CSW.CREATEDATE,C.CONTAINERNAME,CFCI.CREATEDATE CHECKDATE,
csw.checktype,null machineno,null bigworkflowstepid,null bigworkflowstepname
FROM CONTAINERFINISHEDCHECKINFO CFCI
                            
LEFT JOIN CONTAINERSTEPWORKREPORT CSW ON CFCI.CONTAINERFINISHEDCHECKINFOID = CSW.CONTAINERFINISHEDCHECKINFOID
LEFT JOIN CONTAINERSTEPDISPATCH CSD ON CSD.CONTAINERSTEPDISPATCHID = CSW.CONTAINERSTEPDISPATCHID
LEFT JOIN CONTAINER C ON C.CONTAINERID = CSW.CONTAINERID
LEFT JOIN WORKFLOWSTEP WS ON WS.WORKFLOWSTEPID = CSW.WORKFLOWSTEPID
LEFT JOIN CONTAINERSTEPTIMESHEET CST ON CST.CONTAINERCHECKINFOID = CFCI.CONTAINERFINISHEDCHECKINFOID
LEFT JOIN CONTAINERSTEPTIMESHEET CST_ ON CST_.CONTAINERSTEPWORKREPORTID = CSW.CONTAINERSTEPWORKREPORTID

WHERE cfci.createdate>=sysdate-1/24 and nvl2(csw.containerfinishedcheckinfoid,'1','0')='1' and nvl(cst.containersteptimesheetid,'0')='0'
and nvl(cst_.containersteptimesheetid,'0')='0' and csw.isuse=0 and nvl(csd.isuse,0)=0 and cfci.isuse=0 and c.status=1";
            DataTable dt = DatabaseHelper.Query_ReturnDatTable(strsql);
            if (dt.Rows.Count == 0)
            {
                return;
            }
            DataTable newdt = dt.DefaultView.ToTable(true, "FACTORYID");
            newdt.Columns.Add("DJDKDRPG");
            foreach (DataRow dr in newdt.Rows)
            {
                dr["DJDKDRPG"] = GetFactoryAttributes(dr["FACTORYID"].ToString(), "单件多人派工工时平均分配");
            }
            String strValue = "";
            foreach (DataRow r in dt.Rows)
            {
                foreach (DataRow dr in newdt.Rows)
                {
                    if (dr["FACTORYID"].ToString() == r["FACTORYID"].ToString())
                    {
                        strValue = dr["DJDKDRPG"].ToString();
                        break;
                    }
                }
                if (strValue == "是" && Convert.ToString(r["CONTAINERTYPE"]) == "7")//如果是单件单卡多人派工并且是单件单卡检验
                {
                    if (!r.IsNull("CONTAINERSTEPDISPATCHID"))//固定检验没有派工记录
                    {
                        DataTable dt_ = GetDispatchWorkers(r["CONTAINERSTEPDISPATCHID"].ToString());
                        if (dt_.Rows.Count > 0)//如果派工给多人，则分报工数量存储工时
                        {
                            foreach (DataRow dr in dt_.Rows)
                            {
                                r["WORKERID"] = dr["WORKERID"].ToString();
                                AddContainerStepTimeSheetInfo(r, dt_.Rows.Count);
                            }
                            //AddContainerStepTimeSheetInfo(r, dt_);
                        }
                        else
                        {
                            AddContainerStepTimeSheetInfo(r, 1);
                        }
                    }
                    else
                    {
                        AddContainerStepTimeSheetInfo(r, 1);
                    }
                }
                else
                {
                    AddContainerStepTimeSheetInfo(r, 1);
                }
            }
        }

        /// <summary>
        /// 获取工厂的属性信息 create tianFW 2017年11月13日
        /// </summary>
        /// <param name="strFactoryID"></param>
        /// <param name="strAttrName"></param>
        /// <returns></returns>
        private String GetFactoryAttributes(String strFactoryID, String strAttrName)
        {
            StringBuilder strsql = new StringBuilder();
            strsql.AppendLine("SELECT U.ATTRIBUTEVALUE FROM USERATTRIBUTE U");
            strsql.AppendFormat(" WHERE U.PARENTID =  '{0}'", strFactoryID);
            strsql.AppendFormat(" AND U.USERATTRIBUTENAME =  '{0}'", strAttrName);
            Object objValue = DatabaseHelper.GetSingle(strsql.ToString());
            if (objValue == null)
            {
                return "";
            }
            else if (String.IsNullOrWhiteSpace(objValue.ToString()))
            {
                return "";
            }
            else
            {
                return objValue.ToString();
            }
        }

        /// <summary>
        /// 获取单件单卡多人派工的员工信息 create TianFW 2017年11月13日
        /// </summary>
        /// <param name="StepDispatchID"></param>
        /// <returns></returns>
        private DataTable GetDispatchWorkers(String StepDispatchID)
        {
            String strsql = string.Format("SELECT *　FROM CONTAINERSTEPDISPATCHDETAIL CSDD WHERE CSDD.CONTAINERSTEPDISPATCHID='{0}'", StepDispatchID);
            return DatabaseHelper.Query_ReturnDatTable(strsql);
        }

        /// <summary>
        /// 获取总体多人派工的员工信息 add by longb 2023-03-18
        /// </summary>
        /// <param name="StepDispatchID"></param>
        /// <returns></returns>
        private DataTable GetZSDispatchWorkers(String StepDispatchID)
        {
            String strsql = string.Format("SELECT *　FROM CONTAINERSTEPDISPATCHDETAIL_ZS CSDD WHERE CSDD.CONTAINERSTEPDISPATCHID='{0}'", StepDispatchID);
            return DatabaseHelper.Query_ReturnDatTable(strsql);
        }

        #endregion

        #region 检验序自动添加报工记录 create tianFW 该逻辑在工序变更时调用
        /// <summary>
        /// 获取当前序的ControlCode
        /// //add:Wangjh 20180531 增加CONTAINERNAME用于日志
        /// </summary>
        /// <param name="workflowstepID"></param>
        /// <returns></returns>
        private DataTable getWorkflowStepControlCode(string containerID)
        {
            string strsql = String.Format("SELECT CC.CONTAINERID, S.LASTCHECK,CC.CONTAINERNAME FROM CONTAINERCURRENTINFO CC" +
                                          " LEFT JOIN WORKFLOWSTEP WS ON WS.WORKFLOWSTEPID = CC.WORKFLOWSTEPID" +
                                          " LEFT JOIN SPECBASE SB ON SB.SPECBASEID = WS.SPECBASEID" +
                                          " LEFT JOIN SPEC S ON S.SPECID = NVL(SB.REVOFRCDID,WS.SPECID) WHERE CC.CONTAINERID = '{0}'", containerID);
            return DatabaseHelper.Query_ReturnDatTable(strsql);
        }

        /// <summary>
        /// 检验进入下一序的批次工序是不是检验序
        /// </summary>
        /// <param name="containerID"></param>
        /// <returns></returns>
        private Boolean AddContainerStepWorkReportInfo(DataRow dr)
        {
            //DataTable dt = getWorkflowStepControlCode(Convert.ToString(dr["CONTAINERID"]));
            //if (Convert.ToString((dt.Rows[0]["LASTCHECK"])) == "1")
            //{
            //    //LogHelp.WriteLog("批次检验序：" + dr["ContainerID"].ToString() + " " + dr["WORKFLOWSTEPID"].ToString());                                
            //}

            String ContainerStepWorkReportID = System.Guid.NewGuid().ToString();
            if (AddContainerStepWorkReportInfo_dt(dr, ContainerStepWorkReportID))
            {
                if (Convert.ToInt64(dr["CONTAINERTYPE"]) == 3)
                {
                    ContainerStepWorkReportChildDTO newDTO;
                    DataTable dt_child = m_Common.GetContainerInfoByPerContianerID(Convert.ToString(dr["CONTAINERID"]));//子序号
                    if (dt_child.Rows.Count == 0)
                    {
                        return true;
                    }
                    foreach (DataRow r in dt_child.Rows)
                    {
                        newDTO = new ContainerStepWorkReportChildDTO();
                        newDTO.ContainerStepWorkReportID = ContainerStepWorkReportID;
                        newDTO.ChildContainerID = Convert.ToString(r["CONTAINERID"]);
                        m_Workreport.AddContainerStepWorkReportChildInfo(newDTO);
                    }
                }
                return true;
            }
            else
            {
                LogHelp.WriteLog("批次检验序：" + dr["ContainerID"].ToString() + " " + dr["ContainerID"].ToString() + " 添加报工记录失败");
            }

            return false;
        }

        /// <summary>
        /// 创建一个检验序的报工记录
        /// </summary>
        /// <returns></returns>
        private Boolean AddContainerStepWorkReportInfo_dt(DataRow dr, String ContainerStepWorkReportID)
        {
            String strsql = "SELECT CSW.*,CIO.CONTAINERCHECKINFOID FROM CONTAINERSTEPWORKREPORT CSW";
            strsql += " LEFT JOIN CONTAINERCHECKINFO CIO ON CIO.CONTAINERSTEPWORKREPORTID = CSW.CONTAINERSTEPWORKREPORTID and cio.isuse=0 ";
            strsql += string.Format(" WHERE CSW.ISUSE = 0 AND CSW.CONTAINERID='{0}' AND CSW.WORKFLOWSTEPID='{1}'", Convert.ToString(dr["CONTAINERID"]), Convert.ToString(dr["WORKFLOWSTEPID"]));
            DataTable dt = DatabaseHelper.Query_ReturnDatTable(strsql);
            if (dt.Rows.Count > 0)
            {
                if ((string.IsNullOrWhiteSpace(dt.Rows[0]["CONTAINERCHECKINFOID"].ToString())) &&
                    (string.IsNullOrWhiteSpace(dt.Rows[0]["CONTAINERFINISHEDCHECKINFOID"].ToString())))//不存在检验
                {
                    //因不删除记录，则将自动报工记录设置未无效记录 2018年9月29日  
                    //此处不用将批次stepchecknum置为0，因为下面会重新创建批次报工记录，stepchecknum会被置为1 2019/1/16
                    strsql = string.Format("UPDATE CONTAINERSTEPWORKREPORT CSW SET CSW.ISUSE = 1 WHERE CSW.CONTAINERID='{0}' AND CSW.WORKFLOWSTEPID='{1}'", Convert.ToString(dr["CONTAINERID"]), Convert.ToString(dr["WORKFLOWSTEPID"]));
                    int i = DatabaseHelper.ExecuteSql(strsql);//删除报 工数据
                    InsertOracleLog(System.Reflection.MethodBase.GetCurrentMethod().Name, "删除报工数据", i, strsql, dr["CONTAINERNAME"].ToString());//add:Wangjh 20180531 日志记录
                }
                else
                {
                    return false;//存在检验则不再删除也不再创建
                }
            }
            strsql = @" INSERT INTO CONTAINERSTEPWORKREPORT(CONTAINERID,WORKFLOWSTEPID,QTY, CHECKTYPE, CONTAINERSTEPWORKREPORTID, CREATEDATE, ISUSE, ISTRANSFER)
                               VALUES (:CONTAINERID, :WORKFLOWSTEPID,:QTY, 20,:CONTAINERSTEPWORKREPORTID,SYSDATE, 0, 0)";
            OracleParameter[] para = new OracleParameter[4];
            para[0] = DatabaseHelper.NewParameter(":CONTAINERID", Convert.ToString(dr["CONTAINERID"]), OracleType.VarChar);
            para[1] = DatabaseHelper.NewParameter(":WORKFLOWSTEPID", Convert.ToString(dr["WORKFLOWSTEPID"]), OracleType.VarChar);
            para[2] = DatabaseHelper.NewParameter(":QTY", Convert.ToString(dr["QTY"]), OracleType.Number);
            para[3] = DatabaseHelper.NewParameter(":CONTAINERSTEPWORKREPORTID", ContainerStepWorkReportID, OracleType.VarChar);

            int row = DatabaseHelper.ExecuteSql(strsql, para);
            InsertOracleLog(System.Reflection.MethodBase.GetCurrentMethod().Name, "插入报工数据", row, LogHelp.TranferSql(strsql, para), dr["CONTAINERNAME"].ToString());//add:Wangjh 20180531 日志记录
            if (row > 0)
            {
                //检验序自动报工，将stepchecknum置为1
                DatabaseHelper.ExecuteSql(String.Format("UPDATE CONTAINERCURRENTINFO CU SET CU.STEPCHECKNUM=1 WHERE CU.CONTAINERID='{0}'", Convert.ToString(dr["CONTAINERID"])));
                m_Workreport.UpdateWorkReportNum(Convert.ToString(dr["CONTAINERID"]));//更新检验序批次当前序的报工总数
                return true;
            }
            return false;

        }
        #endregion

        #region 处理无效的工时记录 create tianFW 循环处理改为1分钟处理一次 原sync*60
        /// <summary>
        /// 获取工序检无效的检验工时记录
        /// </summary>
        /// <returns></returns>
        private DataTable GetStepCheckLoseStepTimeInfo()
        {
            String strsql = @"SELECT CST.CONTAINERID,CST.WORKFLOWSTEPID,CST.CONTAINERSTEPTIMESHEETID,cst.CONTAINERCHECKINFOID
FROM CONTAINERSTEPTIMESHEET CST
LEFT JOIN CONTAINERCHECKINFO CCI ON CST.CONTAINERCHECKINFOID = CCI.CONTAINERCHECKINFOID
LEFT JOIN CONTAINERFINISHEDCHECKINFO CCIO ON CST.CONTAINERCHECKINFOID = CCIO.CONTAINERFINISHEDCHECKINFOID
WHERE cst.createdate>sysdate-365 and nvl2(CST.CONTAINERCHECKINFOID,'1','0')='1' and not exists (
select 1 from CONTAINERCHECKINFO CCI where cci.containercheckinfoid=cst.containercheckinfoid and cci.isuse=0
union all
select 1 from CONTAINERFINISHEDCHECKINFO CCIO where ccio.containerfinishedcheckinfoid=cst.containercheckinfoid and ccio.isuse=0
)";
            return DatabaseHelper.Query_ReturnDatTable(strsql);
        }

        /// <summary>
        /// 删除无效的工时记录
        /// </summary>
        public void DelLoseStepTimeInfo()
        {
            DataTable dt = GetStepCheckLoseStepTimeInfo();
            if (dt.Rows.Count == 0)
            {
                return;
            }
            Dictionary<string, OracleParameter[]> dic = new Dictionary<string, OracleParameter[]>();
            //add:Wangjh 20180531 
            string sqls = "";
            string containerNames = "";
            //
            foreach (DataRow dr in dt.Rows)
            {
                string temSql = String.Format("DELETE CONTAINERSTEPTIMESHEET CSS WHERE CSS.CONTAINERSTEPTIMESHEETID='{0}'", dr["CONTAINERSTEPTIMESHEETID"]);
                dic.Add(temSql, null);
                temSql = String.Format("DELETE containersteptimesheetsplit CSS WHERE CSS.CONTAINERSTEPTIMESHEETID='{0}'", dr["CONTAINERSTEPTIMESHEETID"]);
                dic.Add(temSql, null);
                //add:Wangjh 20180531 所有sql语句
                sqls = sqls + temSql + ";";
                containerNames = containerNames + dr["CONTAINERID"].ToString() + ";";
                //
            }
            DatabaseHelper.ExecuteSqlTranByHash(dic);
            InsertOracleLog(System.Reflection.MethodBase.GetCurrentMethod().Name, "删除无效的工时记录", dic.Keys.Count, sqls, containerNames);//add:Wangjh 20180531 日志记录
        }
        #endregion

        #region 更新关闭批次变号ChangeContainerid批次name -> id create tianFW 2018年4月18日
        /// <summary>
        /// 获取需要更新记录的名字到ID的批次信息
        ///  add:Wangjh 20180531 增加CONTAINERNAME用于日志
        /// </summary>
        /// <returns></returns>
        private DataTable GetNeedUpdateChangContainerIDtoNameInfo()
        {
            String strsql = @"SELECT C.CONTAINERID, CU.CONTAINERID CHANGECONTAINERID,C.ContainerName
	                            FROM CONTAINERCURRENTINFO C
	                            INNER JOIN CONTAINERCURRENTINFO CU
		                        ON C.CHANGECONTAINERID = CU.CONTAINERNAME
                                WHERE C.CONTAINERSTATUS = 2
	                            AND CU.CONTAINERSTATUS = 1";
            return DatabaseHelper.Query_ReturnDatTable(strsql);
        }

        /// <summary>
        /// 获取需要删除ChangeContainerID的关闭批次信息
        /// add:Wangjh 20180531 增加CONTAINERNAME用于日志
        /// </summary>
        /// <returns></returns>
        private DataTable GetNeedDelChangContainerIDInfo()
        {
            String strsql = @"SELECT C.CONTAINERID,C.ContainerName FROM CONTAINERCURRENTINFO C
	                            LEFT JOIN CONTAINERCURRENTINFO CU ON C.CHANGECONTAINERID = CU.CONTAINERID
                                WHERE C.CONTAINERSTATUS = 2 AND C.CHANGECONTAINERID IS NOT NULL AND CU.CONTAINERID IS NULL";
            return DatabaseHelper.Query_ReturnDatTable(strsql);
        }

        /// <summary>
        /// 更新处理
        /// </summary>
        public void UpdateChangContainerIDtoNameInfo()
        {
            DataTable dt = GetNeedUpdateChangContainerIDtoNameInfo();
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    UpdateChangContainerIDtoNameInfo_dr(dr["CONTAINERID"].ToString(), dr["CHANGECONTAINERID"].ToString(), dr["ContainerName"].ToString());
                }
            }
            DataTable dt_ = GetNeedDelChangContainerIDInfo();
            if (dt_.Rows.Count > 0)
            {
                foreach (DataRow dr in dt_.Rows)
                {
                    UpdateChangContainerIDtoNameInfo_dr(dr["CONTAINERID"].ToString(), "", dr["ContainerName"].ToString());
                }
            }
        }

        /// <summary>
        /// 数据更新
        /// </summary>
        /// <param name="containerid"></param>
        /// <param name="newcontainerid"></param>
        /// <returns></returns>
        private Boolean UpdateChangContainerIDtoNameInfo_dr(string containerid, string newcontainerid, string containerName)
        {
            String strsql = string.Format("UPDATE CONTAINERCURRENTINFO C SET C.CHANGECONTAINERID = '{0}' WHERE C.CONTAINERID='{1}' ", newcontainerid, containerid);
            int i = DatabaseHelper.ExecuteSql(strsql);
            InsertOracleLog(System.Reflection.MethodBase.GetCurrentMethod().Name, "更新关闭批次变号", i, strsql, containerName);//add:Wangjh 20180531 日志记录
            if (i > 0)
            {
                return true;
            }
            return false;
        }
        #endregion

        #region 移到下序后班组派工更新 create:Wangjh
        /// <summary>
        /// 更新班组派工的sql
        /// </summary>
        /// <returns></returns>
        void UpdateTeamInfoOfNextSpec(DataRow dr)
        {
            string strSql = "";
            DataTable teamDtOfSpec = TeamInfoOfSpec(dr);

            DataTable teamDtOfDispatch = TeamInfoOfDispatch(dr);//班组派工相关信息
            //批次班组派工
            DataView dataView = teamDtOfDispatch.DefaultView;
            dataView.RowFilter = "workflowstepid is null";
            DataTable teamDtOfContainer = dataView.ToTable();
            //批次工序班组派工
            dataView = teamDtOfDispatch.DefaultView;
            dataView.RowFilter = "workflowstepid is not null";
            DataTable teamDtOfSpecDispatch = dataView.ToTable();

            string specBaseTeam = "";
            if (teamDtOfSpec.Rows.Count > 0 && (!teamDtOfSpec.Rows[0].IsNull("TEAMID"))) //工序本身有班组信息
            {
                strSql = string.Format(" TEAMID='{0}',TEAMNAME='{1}',Teamdispatchid=''",
                                       Convert.ToString(teamDtOfSpec.Rows[0]["teamid"]), Convert.ToString(teamDtOfSpec.Rows[0]["TEAMNAME"]));

                if (teamDtOfContainer.Rows.Count > 0 || teamDtOfSpecDispatch.Rows.Count > 0)
                {
                    strSql += " ,Teamdispatchnum=1";//存在班组派工
                }
                else
                {
                    strSql += " ,Teamdispatchnum=0";//不存在班组派工
                }
                specBaseTeam = "1";
            }
            if (teamDtOfContainer.Rows.Count > 0)//存在批次班组派工
            {
                strSql = string.Format(" TEAMID='{0}',TEAMNAME='{1}',Teamdispatchid='{2}',Teamdispatchnum=1",
                                       Convert.ToString(teamDtOfContainer.Rows[0]["teamid"]), Convert.ToString(teamDtOfContainer.Rows[0]["TEAMNAME"]), Convert.ToString(teamDtOfContainer.Rows[0]["containerteamdispatchid"]));
            }
            if (teamDtOfSpecDispatch.Rows.Count > 0)//存在批次工序班组派工
            {
                DataRow[] currentSpecDt = teamDtOfSpecDispatch.Select(" workflowstepid='" + Convert.ToString(dr["workflowstepid"]) + "'");//筛选当前工序的派工
                if (currentSpecDt.Length > 0)
                {
                    strSql = string.Format(" TEAMID='{0}',TEAMNAME='{1}',Teamdispatchid='{2}',Teamdispatchnum=1",
                                           Convert.ToString(currentSpecDt[0]["teamid"]), Convert.ToString(currentSpecDt[0]["TEAMNAME"]), Convert.ToString(currentSpecDt[0]["containerteamdispatchid"]));
                }
                else
                {
                    if (specBaseTeam == "")//工序本身无班组
                        strSql = " TEAMID='',TEAMNAME='',Teamdispatchid='',Teamdispatchnum=1";
                }

            }
            if (strSql == "")
            {
                strSql = " TEAMID='',TEAMNAME='',Teamdispatchid='',Teamdispatchnum=0";
            }
            //return strSql;
            strSql = string.Concat("update containercurrentinfo cci set ", strSql);
            strSql = string.Concat(strSql, " where containerid='" + dr["containerid"].ToString() + "'");
            DatabaseHelper.ExecuteSql(strSql);
        }
        /// <summary>
        /// 工序本身有班组信息
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        DataTable TeamInfoOfSpec(DataRow dr)
        {
            DataTable teamDtOfSpec = new DataTable();
            string strSql = @" SELECT ws.teamid,t.teamname FROM workflowstep ws 
                                LEFT JOIN team t ON t.teamid=ws.teamid";
            strSql += string.Format(" WHERE ws.workflowstepid='{0}'", Convert.ToString(dr["WorkFlowStepID"]));

            teamDtOfSpec = DatabaseHelper.Query_ReturnDatTable(strSql);

            return teamDtOfSpec;

        }

        /// <summary>
        /// 派到班组的
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        DataTable TeamInfoOfDispatch(DataRow dr)
        {
            DataTable teamDtOfSpecDispatch = new DataTable();
            string strSql = @" SELECT ctd.teamid,t.teamname,ctd.containerteamdispatchid,ctd.workflowstepid FROM containerteamdispatch ctd 
                                LEFT JOIN team t ON t.teamid=ctd.teamid";
            strSql += string.Format(" WHERE ctd.containerid='{0}'  AND ctd.isuse=0", Convert.ToString(dr["ContainerID"]));

            teamDtOfSpecDispatch = DatabaseHelper.Query_ReturnDatTable(strSql);

            return teamDtOfSpecDispatch;
        }
        #endregion

        #region 更新批次当前序后所有序的班组ID信息 create wangjh 2017/10/30
        /// <summary>
        /// 获取批次当前工序后所有班组,工区信息
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        DataTable GetTeamIDsAndWorkcenters(DataRow dr)
        {
            string strSql = @" select listagg(workcenterid,',') WITHIN GROUP (ORDER BY null) workcenterids,
listagg(teamid,',') WITHIN GROUP (ORDER BY null) teamids  from (
SELECT wfs.WORKCENTERID,ctd.teamid FROM WORKFLOWSTEP WFS
LEFT JOIN WORKFLOW WF ON WF.WORKFLOWID = WFS.WORKFLOWID
left join CONTAINERTEAMDISPATCH CTD on ctd.containerid='{2}' and ctd.workflowstepid=wfs.workflowstepid
WHERE  WF.WORKFLOWID = '{0}' and WFS.SEQUENCE >= {1} ";
            strSql = string.Format(strSql, dr["WORKFLOWID"].ToString(), dr["WORKFLOWSTEPSEQUENCE"], dr["CONTAINERID"].ToString());
            strSql += @"group by wfs.WORKCENTERID,ctd.teamid )";
            DataSet myDt = DatabaseHelper.Query(strSql);
            if (myDt == null || myDt.Tables.Count == 0)
            {
                return null;
            }
            return myDt.Tables[0];
        }
        /// <summary>
        /// 更新批次当前序后的工区和班组ids字段
        /// add:Wangjh 20230710
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        Boolean UpdateConWorkcenterIdsAndTeamids(DataRow dr)
        {
            DataTable dt = GetTeamIDsAndWorkcenters(dr);

            string strsql = string.Format(" UPDATE CONTAINERCURRENTINFO CCI SET CCI.STEPTEAMIDS='{0}',cci.Stepworkcenterids='{1}' WHERE CCI.CONTAINERID='{2}'",
                dt.Rows[0]["teamids"].ToString(), dt.Rows[0]["workcenterids"].ToString(), dr["CONTAINERID"]);

            if (DatabaseHelper.ExecuteSql(strsql) > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region "补全无机型的批次 create:Wangjh"
        /// <summary>
        /// 获取总表无机型的批次
        /// </summary>
        /// <returns></returns>
        DataTable GetContainerOfNoBatch()
        {
            string strSql = @" SELECT cci.containerid,REPLACE( SUBSTR(c.mfgbatch,4),'|',' ') familylistnames,CCI.ContainerName  FROM container c 
                                INNER JOIN  containercurrentinfo cci ON cci.containerid=c.containerid
                                WHERE cci.familylistnames IS NULL and trim(REPLACE( SUBSTR(c.mfgbatch,4),'|',' ')) is not null";
            DataSet myDt = DatabaseHelper.Query(strSql);
            if (myDt == null || myDt.Tables.Count == 0)
            {
                return null;
            }
            return myDt.Tables[0];
        }
        /// <summary>
        /// 更新每行机型
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        Boolean UpdateNoBatchOfRow(DataRow dr)
        {
            string updateSql = @" UPDATE containercurrentinfo cci SET cci.familylistnames=:familylistnames WHERE cci.containerid=:containerid";
            OracleParameter[] updateParam = new OracleParameter[2];
            updateParam[0] = DatabaseHelper.NewParameter(":familylistnames", dr["familylistnames"].ToString().Trim(), OracleType.VarChar);
            updateParam[1] = DatabaseHelper.NewParameter(":containerid", dr["containerid"], OracleType.VarChar);
            int i = DatabaseHelper.ExecuteSql(updateSql, updateParam);
            InsertOracleLog(System.Reflection.MethodBase.GetCurrentMethod().Name, "更新批次机型", i, LogHelp.TranferSql(updateSql, updateParam), dr["CONTAINERNAME"].ToString());//add:Wangjh 20180531 日志记录
            if (i > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 更新所有无机型的批次
        /// </summary>
        public void UpdateContainerOfNoBatch()
        {
            DataTable containerData = GetContainerOfNoBatch();
            if (containerData.Rows.Count > 0)
            {
                foreach (DataRow dr in containerData.Rows)
                {
                    if (UpdateNoBatchOfRow(dr) == false)
                    {
                        return;
                    }
                }
            }
        }

        #endregion

        #region 自动工序班组派工 add:Wangjh 20180205
        /// <summary>
        /// 获取基础数据的班组派工记录信息(前提是传入的批次没有班组派工的情况下)
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        DataTable GetRecentTeamDispatchOfProduct(DataRow dr)
        {

            // 检查传入的批次是否已经有班组派工了
            //            string checkSql = @"select CTD.CONTAINERTEAMDISPATCHID from containerteamdispatch ctd
            //	                        LEFT JOIN WORKFLOWSTEP WS ON WS.WORKFLOWSTEPID=CTD.WORKFLOWSTEPID
            //                            ";
            //            checkSql += string.Format(" where ctd.containerid='{0}' AND WS.WORKFLOWID='{1}'", dr["containerid"].ToString(), dr["WORKFLOWID"].ToString());
            //            if (DatabaseHelper.Query_ReturnDatTable(checkSql).Rows.Count > 0)
            //                return null;
            //


            //获取批次工艺上有班组信息的工序add:20180309
            string strSql = @"
                            SELECT WS.WORKFLOWSTEPID,T.TEAMID,WC.WORKCENTERID,NULL CONTAINERID,NULL FACTORYID,NULL SHIFTID FROM WORKFLOW W 
                            LEFT JOIN WORKFLOWSTEP WS ON WS.WORKFLOWID=W.WORKFLOWID
                            LEFT JOIN TEAM T ON T.TEAMID=WS.TEAMID
                            LEFT JOIN WORKCENTER WC ON WC.WORKCENTERID=T.WORKCENTERID
                            WHERE W.WORKFLOWID='{0}' and T.TEAMID IS NOT NULL and not exists (
select 1 from containerteamdispatch ctd where ctd.containerid='{1}' and ctd.workflowstepid=ws.workflowstepid and ctd.isuse=0
) ";
            strSql = string.Format(strSql, dr["WORKFLOWID"].ToString(), dr["containerid"].ToString());

            DataTable dt = DatabaseHelper.Query_ReturnDatTable(strSql);

            //string subSql = @"SELECT distinct swc.subworkflowid FROM subworkflowcheckinfo swc";
            //subSql += string.Format(" WHERE swc.containerid='{0}' AND swc.workflowid='{1}'", dr["ContainerID"].ToString(), dr["WORKFLOWID"].ToString());
            //DataTable subDt = DatabaseHelper.Query_ReturnDatTable(subSql);
            //foreach (DataRow _dr in subDt.Rows)
            //{
            //    condition = string.Format(" AND W.WORKFLOWID='{0}'", _dr["subworkflowid"].ToString());
            //    DataTable _dt = DatabaseHelper.Query_ReturnDatTable(strSql + condition);
            //    if (_dt.Rows.Count > 0)
            //        dt.Merge(_dt);
            //}
            //dt.AcceptChanges();

            return dt;
        }
        /// <summary>
        /// 插入班组派工信息
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        Boolean InsertContainerTeamDispatchInfo(DataRow dr)
        {
            //            string strSql = @"begin
            //    delete CONTAINERTEAMDISPATCH where CONTAINERID=:containerid and workflowstepid=:workflowstepid;
            //    INSERT INTO CONTAINERTEAMDISPATCH(CONTAINERID,FACTORYID,WORKCENTERID,TEAMID,SHIFTID,WORKFLOWSTEPID,CONTAINERTEAMDISPATCHID,EMPLOYEEID,CREATEDATE,ISUSE,ISTRANSFER)
            //    VALUES(:containerid,:factoryid,:workcenterid,:TEAMID,:shiftid,:workflowstepid,:containerteamdispatchid,null,sysdate,0,1);
            //end; ";
            string strSql = @"INSERT INTO CONTAINERTEAMDISPATCH(CONTAINERID,FACTORYID,WORKCENTERID,TEAMID,SHIFTID,WORKFLOWSTEPID,CONTAINERTEAMDISPATCHID,EMPLOYEEID,CREATEDATE,ISUSE,ISTRANSFER)
    VALUES(:containerid,:factoryid,:workcenterid,:TEAMID,:shiftid,:workflowstepid,:containerteamdispatchid,null,sysdate,0,1)";
            OracleParameter[] insertPara = new OracleParameter[7];
            insertPara[0] = DatabaseHelper.NewParameter(":containerid", dr["CONTAINERID"], OracleType.VarChar);
            insertPara[1] = DatabaseHelper.NewParameter(":factoryid", dr["factoryid"], OracleType.VarChar);
            insertPara[2] = DatabaseHelper.NewParameter(":workcenterid", dr["workcenterid"], OracleType.VarChar);
            insertPara[3] = DatabaseHelper.NewParameter(":shiftid", dr["shiftid"], OracleType.VarChar);
            insertPara[4] = DatabaseHelper.NewParameter(":workflowstepid", dr["workflowstepid"], OracleType.VarChar);
            insertPara[5] = DatabaseHelper.NewParameter(":containerteamdispatchid", Guid.NewGuid().ToString(), OracleType.VarChar);
            insertPara[6] = DatabaseHelper.NewParameter(":TEAMID", dr["TEAMID"], OracleType.VarChar);

            DatabaseHelper.ExecuteSql(string.Format(" delete CONTAINERTEAMDISPATCH where CONTAINERID='{0}' and workflowstepid='{1}' ", dr["CONTAINERID"].ToString(), dr["workflowstepid"].ToString()));
            int i = 0;
            try
            {
                i = DatabaseHelper.ExecuteSql(strSql, insertPara);
                //InsertOracleLog(System.Reflection.MethodBase.GetCurrentMethod().Name, "自动班组派工工序" + dr["workflowstepid"], i, LogHelp.TranferSql(strSql, insertPara), dr["CONTAINERNAME"].ToString());//add:Wangjh 20180531 日志记录

            }
            catch (Exception ex)
            {
                LogHelp.WriteError("批次自动班组派工信息:" + LogHelp.TranferSql(strSql, insertPara) + ex.Message, ex);
                //InsertOracleLog(System.Reflection.MethodBase.GetCurrentMethod().Name, "自动班组派工工序异常" + ex.Message + dr["workflowstepid"], i, LogHelp.TranferSql(strSql, insertPara), dr["CONTAINERNAME"].ToString());//add:Wangjh 20180531 日志记录
            }

            if (i > 0)
                return true;
            else
                return false;
        }
        /// <summary>
        /// 自动班组派工
        /// </summary>
        /// <param name="dr"></param>
        void AutoContainerTeamDispatchInfo(DataRow dr)
        {
            if (dr["ISINSTORE"].ToString() == "-1")
            {
                return;
            }
            string strAttr = m_Common.GetFatoryAttributes(dr["ORIGINALFACTORYID"].ToString(), "默认班组派工");
            if (strAttr != "是") //需要进行自动班组派工
            {
                return;
            }
            DataTable latestTeamDispatch = GetRecentTeamDispatchOfProduct(dr);
            if (latestTeamDispatch == null || latestTeamDispatch.Rows.Count == 0)
            {
                return;
            }
            latestTeamDispatch.Columns.Add("ContainerName");
            foreach (DataRow ldr in latestTeamDispatch.Rows)
            {
                ldr["containerid"] = dr["containerid"];
                ldr["FACTORYID"] = dr["ORIGINALFACTORYID"];
                ldr["ContainerName"] = dr["ContainerName"];
                if (InsertContainerTeamDispatchInfo(ldr) == false)
                    return;
            }
        }

        #endregion

        #region 自动更新产品描述、工序分厂等其他基础信息 20180207

        /// <summary>
        /// 获取更改过基础数据工序分厂或产品描述
        /// </summary>
        /// <returns></returns>
        DataTable GetDifferDes()
        {
            string strSql = @"
SELECT cci.ContainerName,cci.bomid ccibomid,cci.isinstore,cci.factoryname,cci.containerid,p.description,
cci.productdescription,s.factoryid,cci.specfactoryid,C.status,cci.containerstatus,cci.planqty cciplanqty,m.qty planqty  FROM containercurrentinfo cci
LEFT JOIN product p ON p.productid=cci.productid
LEFT JOIN spec s ON s.specid=cci.specid
LEFT JOIN CONTAINER C ON C.CONTAINERID=CCI.CONTAINERID
LEFT JOIN mfgorder m ON m.mfgorderid=cci.mfgorderid
WHERE cci.factoryname not like '装配试车%' and cci.productdescription<>p.description
 OR s.factoryid<>cci.specfactoryid OR (s.factoryid IS NOT NULL AND cci.specfactoryid IS NULL) OR m.qty <>cci.planqty
      ";
            return DatabaseHelper.Query_ReturnDatTable(strSql);
        }
        /// <summary>
        /// 更新每行的工序分厂或产品描述
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        Boolean UpdateDes(DataRow dr)
        {
            //string strSql = "UPDATE containercurrentinfo cci SET cci.productdescription=:productdescription,cci.specfactoryid=:specfactoryid,CONTAINERSTATUS=:CONTAINERSTATUS WHERE cci.containerid=:containerid";
            //OracleParameter[] updatePara = new OracleParameter[4];
            //updatePara[0] = DatabaseHelper.NewParameter(":CONTAINERID", dr["CONTAINERID"], OracleType.VarChar);
            //updatePara[1] = DatabaseHelper.NewParameter(":productdescription", dr["description"].ToString (), OracleType.VarChar);
            //updatePara[2] = DatabaseHelper.NewParameter(":specfactoryid", dr["factoryid"].ToString(), OracleType.VarChar);
            //updatePara[3] = DatabaseHelper.NewParameter(":CONTAINERSTATUS", dr["status"].ToString(), OracleType.VarChar);
            //int i = DatabaseHelper.ExecuteSql(strSql, updatePara);
            //if (i > 0)
            //    return true;
            //else
            //    return false;
            string strSql = @"UPDATE containercurrentinfo cci SET cci.containerid=cci.containerid";
            if (dr["description"] != dr["productdescription"])
                strSql += string.Format(",cci.productdescription='{0}'", dr["description"]);
            if (dr["factoryid"] != dr["specfactoryid"])
                strSql += string.Format(",cci.specfactoryid='{0}'", dr["factoryid"]);
            if (dr["status"] != dr["containerstatus"])
                strSql += string.Format(",cci.containerstatus='{0}'", dr["status"]);
            if (dr["planqty"] != dr["cciplanqty"])
                strSql += string.Format(",cci.planqty='{0}'", dr["planqty"]);

            strSql += string.Format("where cci.containerid='{0}'", dr["containerid"]);
            int i = DatabaseHelper.ExecuteSql(strSql);
            InsertOracleLog(System.Reflection.MethodBase.GetCurrentMethod().Name, "更新批次某些更改的基础数据", i, strSql, dr["CONTAINERNAME"].ToString());//add:Wangjh 20180531 日志记录
            if (i > 0)
                return true;
            else
                return false;
        }
        /// <summary>
        /// 更新不同工序分厂或产品描述
        /// </summary>
        public void UpdateDifferDes()
        {
            DataTable dt = GetDifferDes();
            if (dt.Rows.Count == 0)
                return;
            foreach (DataRow dr in dt.Rows)
            {
                UpdateDes(dr);
            }
        }

        #endregion

        #region 更新领料时间 create:Wangjh
        /// <summary>
        /// 获取领料时间
        /// </summary>
        /// <returns></returns>
        DataTable GetMaterialDateInfo()
        {
            string strSql = @"SELECT HML.TXNDATE materialDate,null MATERIALEMPLOYEEID,cci.CONTAINERID,cci.containername FROM HISTORYMAINLINE HML
                        LEFT JOIN WORKFLOWSTEP WS2 ON WS2.WORKFLOWSTEPID=HML.WORKFLOWSTEPID
                        LEFT JOIN CDODEFINITION CDO ON CDO.CDODEFID=HML.TXNTYPE 
                        INNER JOIN containercurrentinfo cci ON cci.containerid=hml.containerid
                        WHERE WS2.WORKFLOWSTEPNAME='到料确认' AND (CDO.CDONAME='MoveStd' OR CDO.CDONAME='MoveNonStd')
                        AND cci.materialdate IS NULL and hml.txndate IS NOT NULL";

            return DatabaseHelper.Query_ReturnDatTable(strSql);
        }
        /// <summary>
        /// 更新每行领料时间
        /// </summary>
        /// <param name="dr"></param>
        private Boolean UpdateMaterialOfRow(DataRow dr)
        {
            string updateSql = @" UPDATE containercurrentinfo cci SET cci.isinstore=cci.isinstore";

            if (!dr.IsNull("materialdate"))
            {
                updateSql += ",cci.materialdate=to_date('" + dr["materialDate"].ToString() + "','yyyy/mm/dd hh24:mi:ss')";
            }
            if (!dr.IsNull("MATERIALEMPLOYEEID"))
            {
                updateSql += ",cci.MATERIALEMPLOYEEID='" + dr["MATERIALEMPLOYEEID"].ToString() + "'";
            }
            updateSql += "  WHERE cci.containerid=:containerid";
            OracleParameter[] updatePara = new OracleParameter[1];
            updatePara[0] = DatabaseHelper.NewParameter(":CONTAINERID", dr["CONTAINERID"], OracleType.VarChar);
            int i = DatabaseHelper.ExecuteSql(updateSql, updatePara);
            InsertOracleLog(System.Reflection.MethodBase.GetCurrentMethod().Name, "更新领料时间", i, LogHelp.TranferSql(updateSql, updatePara), dr["CONTAINERNAME"].ToString());
            if (i > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取领用人信息
        /// </summary>
        /// <returns></returns>
        DataTable GetMaterialEmployee()
        {
            string strSql = @"SELECT null materialDate,e.employeeid MATERIALEMPLOYEEID,cci.CONTAINERID,cci.containername FROM containercurrentinfo cci
                            LEFT JOIN Userattribute ut ON ut.parentid=cci.containerid AND ut.userattributename='领用人'
                            LEFT JOIN employee  e ON e.fullname=ut.attributevalue
                            WHERE cci.materialdate IS NOT NULL AND e.employeeid IS NOT NULL AND cci.MATERIALEMPLOYEEID IS NULL and rownum<1001";
            return DatabaseHelper.Query_ReturnDatTable(strSql);

        }

        /// <summary>
        /// 更新所有领料时间
        /// </summary>
        public void UpdateMaterial()
        {
            DataTable containerData = GetMaterialDateInfo();
            if (containerData.Rows.Count > 0)
            {
                foreach (DataRow dr in containerData.Rows)
                {
                    if (UpdateMaterialOfRow(dr) == false)
                    {
                        return;
                    }
                }
            }
            containerData = GetMaterialEmployee();
            foreach (DataRow dr in containerData.Rows)
            {
                if (UpdateMaterialOfRow(dr) == false)
                {
                    return;
                }
            }

        }



        #endregion

        #region 检测分批出批次的原批次是否有已接收的转工信息 add:Wangjh 20180313
        /// <summary>
        /// 获取原始批次的转工标记信息
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        DataTable GetOriginContainerShip(DataRow dr)
        {
            string strSql = @"SELECT cci.shipid,cci.shipnum,cci.isship,CCI.FACTORYID,CCI.FACTORYNAME,CCI.WORKCENTERID,CCI.WORKCENTERNAME,
                            CCI.WORKFLOWSTEPID,CCI.ContainerName FROM CONTAINERCURRENTINFO CCI ";
            strSql += string.Format(" LEFT JOIN containersplitinfo  csi ON csi.containerid=cci.containerid AND csi.splitcontainername='{0}' ", dr["containername"].ToString());
            strSql += " WHERE (CCI.SHIPNUM='5' OR CCI.SHIPNUM='6') AND cci.isship='1'";
            strSql += string.Format(" AND CCI.CONTAINERid='{0}' and csi.workflowstepid='{1}'", dr["splitfromid"].ToString(), dr["workflowstepid"].ToString());
            return DatabaseHelper.Query_ReturnDatTable(strSql);
        }
        /// <summary>
        /// 更新分批出流水卡的转工标记
        /// </summary>
        /// <param name="dr"></param>
        void UpdateSplitContainerShip(DataRow dr)
        {
            DataTable dt = GetOriginContainerShip(dr);
            if (dt.Rows.Count == 0)
                return;
            DataRow shipRow = dt.Rows[0];
            //自动插入一条分批批次的转工记录
            string insertSql = @"begin  
            for x in (select * from containershiprecord csr where csr.containershiprecordid='{0}' and csr.isuse=0)
              loop
                INSERT INTO CONTAINERSHIPRECORD(PROPOSERID,PREPOSERDATE,ISUSE,CONTAINERSHIPRECORDID,FACTORYID,CONTAINERID,WORKFLOWSTEPID,TOWORKFLOWSTEPID,  AUDITDATE,AUDITOR,AUDITRESULT,TOFACTORYID,ISTRANSFER,
                Toacceptdate,TOACCEPTOR,TOWORKCENTERID,estimatedcompletedate)
                VALUES (x.proposerid,x.preposerdate,0,'{1}',x.factoryid,'{2}',x.workflowstepid,x.toworkflowstepid,x.auditdate,x.auditor,x.auditresult,x.tofactoryid,x.istransfer,x.toacceptdate,x.toacceptor,x.toworkcenterid,
                x.estimatedcompletedate);
              end loop;
              
            for x2 in (select * from containershiprecordstep csrs where csrs.containershiprecordid='{0}')
              loop
                insert into containershiprecordstep csrs (csrs.containershiprecordid,csrs.workflowstepid) values ('{1}',x2.workflowstepid);
              end loop
            commit;
            end;";

            string shipId = Guid.NewGuid().ToString();

            DatabaseHelper.ExecuteSql(string.Format(insertSql, shipRow["SHIPID"].ToString(), shipId, dr["CONTAINERID"].ToString()));

            string updateSql = @"UPDATE CONTAINERCURRENTINFO CCI SET CCI.ISSHIP=1,CCI.SHIPNUM=:SHIPNUM,CCI.SHIPID=:SHIPID,CCI.WORKCENTERID=:WORKCENTERID,CCI.WORKCENTERNAME=:WORKCENTERNAME, 
                                CCI.FACTORYID=:FACTORYID,CCI.FACTORYNAME=:FACTORYNAME
                                    WHERE CCI.CONTAINERID=:CONTAINERID AND CCI.WORKFLOWSTEPID=:WORKFLOWSTEPID";
            OracleParameter[] updatePara = new OracleParameter[8];
            updatePara[0] = DatabaseHelper.NewParameter(":CONTAINERID", dr["CONTAINERID"], OracleType.VarChar);
            updatePara[1] = DatabaseHelper.NewParameter(":SHIPNUM", shipRow["SHIPNUM"], OracleType.VarChar);
            updatePara[2] = DatabaseHelper.NewParameter(":SHIPID", shipId, OracleType.VarChar);
            updatePara[3] = DatabaseHelper.NewParameter(":WORKCENTERID", shipRow["WORKCENTERID"], OracleType.VarChar);
            updatePara[4] = DatabaseHelper.NewParameter(":WORKCENTERNAME", shipRow["WORKCENTERNAME"], OracleType.VarChar);
            updatePara[5] = DatabaseHelper.NewParameter(":FACTORYID", shipRow["FACTORYID"], OracleType.VarChar);
            updatePara[6] = DatabaseHelper.NewParameter(":FACTORYNAME", shipRow["FACTORYNAME"], OracleType.VarChar);
            updatePara[7] = DatabaseHelper.NewParameter(":WORKFLOWSTEPID", shipRow["WORKFLOWSTEPID"], OracleType.VarChar);
            int i = DatabaseHelper.ExecuteSql(updateSql, updatePara);
            InsertOracleLog(System.Reflection.MethodBase.GetCurrentMethod().Name, "更新分批出流水卡的转工标记", i, LogHelp.TranferSql(updateSql, updatePara), dr["CONTAINERNAME"].ToString());//add:Wangjh 20180531 日志记录

        }

        #endregion

        #region 补充已经在转工序但无转工记录批次的转工(处理功能界面没成功的) add:Wangjh 20180411
        /// <summary>
        /// 获取已经在转工序但是无自动转工的记录
        /// </summary>
        /// <returns></returns>
        DataTable GetNoShipContainer(DataRow specDr)
        {
            string strSql = @"
                            SELECT cci.ContainerName,cci.containerid,cci.qty,cci.workflowstepid,cci.workflowid,cci.workflowstepsequence,cci.originalfactoryid FROM containercurrentinfo cci
                            LEFT JOIN containershiprecord csr ON csr.containerid=cci.containerid AND csr.workflowstepid=cci.workflowstepid AND CSR.ISUSE=0
                            LEFT JOIN container c ON c.containerid=cci.containerid
                            left join factory fa on fa.factoryid=cci.specfactoryid
                             LEFT JOIN Workflow w ON w.workflowid=cci.workflowid
                            WHERE c.originalfactoryid=w.factoryid and cci.specfactoryid<>cci.originalfactoryid and fa.factoryid is not null AND cci.isship=0 AND cci.isinstore=0 AND csr.containershiprecordid IS NULL
                            ";
            if ((!specDr.IsNull("containerid")) && (!specDr.IsNull("workflowstepid")))
            {
                strSql += string.Format(" AND CCI.containerid='{0}' and cci.workflowstepid='{1}'", specDr["containerid"].ToString(), specDr["workflowstepid"].ToString());
            }

            return DatabaseHelper.Query_ReturnDatTable(strSql);
        }

        /// <summary>
        /// 获取已经在转工序但是无自动转工的记录,当前工艺在子工艺
        /// </summary>
        /// <returns></returns>
        DataTable GetNoShipContainer2(DataRow specDr)
        {
            string strSql = @"                          
                            SELECT cci.containername,s.specno,wb.workflowname,cci.containerid,cci.qty,ws.workflowstepid,ws.workflowid,ws.sequence workflowstepsequence,cci.originalfactoryid FROM containercurrentinfo cci
                            LEFT JOIN subworkflowcheckinfo swc ON swc.containerid=cci.containerid AND swc.subworkflowid=cci.workflowid
                            LEFT JOIN workflow cciw ON cciw.workflowid=cci.workflowid--当前工艺，在子工艺里面
                            LEFT JOIN Workflowbase cciwb ON cciwb.workflowbaseid=cciw.workflowbaseid                            
                            LEFT JOIN Workflowstep ws ON ws.workflowid=swc.workflowid AND (ws.subworkflowid=cci.workflowid OR cciwb.workflowbaseid=ws.subworkflowbaseid) --主工艺的工序
                            LEFT JOIN specbase sb ON sb.specbaseid=ws.specbaseid
                            LEFT JOIN spec s ON s.specid=NVL(sb.revofrcdid,ws.specid)
                            LEFT JOIN Workflow w ON w.workflowid=ws.workflowid
                            LEFT JOIN Workflowbase wb ON wb.workflowbaseid=w.workflowbaseid
                            LEFT JOIN containershiprecord csr ON csr.containerid=cci.containerid AND csr.workflowstepid=ws.workflowstepid and csr.isuse=0
                            left join containershiprecive csre on csre.containershiprecordid=csr.containershiprecordid and csre.isuse=0
                            WHERE ws.workflowstepid IS NOT NULL  AND  cci.originalfactoryid<>cciw.factoryid AND (csr.containershiprecordid IS NULL OR (CSR.containershiprecordid IS NOT  NULL AND (CSRE.Recivedate IS  NULL /*OR (SYSDATE-csre.recivedate)*24*60<5*/ )))  AND cci.isship=0 AND CCI.SHIPNUM=0 AND cci.isinstore=0 
                            ";
            if ((!specDr.IsNull("containerid")) && (!specDr.IsNull("workflowstepid")))
            {
                strSql += string.Format(" AND CCI.containerid='{0}' and cci.workflowstepid='{1}'", specDr["containerid"].ToString(), specDr["workflowstepid"].ToString());
            }
            strSql += @" GROUP BY cci.containername,s.specno,wb.workflowname,cci.containerid,cci.qty,ws.workflowstepid,ws.workflowid,ws.sequence,cci.originalfactoryid
                            order by ws.sequence asc";
            return DatabaseHelper.Query_ReturnDatTable(strSql);
        }
        /// <summary>
        /// 是否已存在转工
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        int IsExitShipRecord(DataRow dr)
        {

            string strSql = @"SELECT CSRE.RECIVEDATE,csr.* FROM containershiprecord csr
                            LEFT JOIN Workflowstep ws ON ws.workflowstepid=csr.workflowstepid
                            LEFT JOIN workflow w ON w.workflowid=ws.workflowid
                            LEFT JOIN workflowbase wb ON wb.workflowbaseid=w.workflowbaseid
                            LEFT JOIN specbase sb ON sb.specbaseid=ws.specbaseid
                            LEFT JOIN spec  s ON s.specid=NVL(sb.specbaseid,ws.specid)
                            LEFT JOIN containershiprecive CSRE ON CSRE.containershiprecordID=CSR.containershiprecordID and csre.isuse=0
                            ";
            strSql += string.Format(" WHERE csr.isuse=0 and csr.containerid='{0}' AND wb.workflowname='{1}'", dr["containerid"], dr["workflowname"]);
            if (!dr.IsNull("workflowstepid"))
            {
                strSql += string.Format(" AND ws.workflowstepid='{0}'", dr["workflowstepid"]);
            }
            if (dr.IsNull("specno"))
            {
                strSql += string.Format(" AND ws.sequence='{0}'", dr["workflowstepsequence"]);
            }
            else
            {
                strSql += string.Format(" and  s.specno='{0}'", dr["specno"]);
            }
            DataTable dt = DatabaseHelper.Query_ReturnDatTable(strSql);
            if (dt.Rows.Count == 0)
            {
                return 0;//不存在转工
            }
            else if (dt.Rows.Count > 0 && dt.Rows[0].IsNull("RECIVEDATE"))
            {
                return 1;//有转工且未转入
            }
            else //if (dt.Rows.Count > 0 && dt.Rows[0].IsNull("RECIVEDATE")==false )
            {
                return 2;//有转工且转入
            }
        }

        /// <summary>
        /// 补充自动转工记录
        /// </summary>
        public void SupplyAutoShip(DataRow specDr)
        {
            DataTable normalShipDt = GetNoShipContainer(specDr);//正常需要转工的序
            // DataTable faStepShipDt = GetNoShipContainer2(specDr);//需要转工父工序的记录，当前在子工艺里
            if (normalShipDt.Rows.Count == 0)// && faStepShipDt.Rows.Count == 0
                return;
            Dictionary<string, string> para = new Dictionary<string, string>();
            // DataTable faShipContainerDt = faStepShipDt.DefaultView.ToTable(true, "CONTAINERID");
            foreach (DataRow dr in normalShipDt.Rows)
            {
                para["ContainerID"] = dr["ContainerID"].ToString();
                para["WorkFlowStepID"] = dr["WorkFlowStepID"].ToString();
                para["UserInfoFactory"] = dr["originalfactoryid"].ToString();//用户当前分厂，此处默认为开卡分厂
                para["WorkflowID"] = dr["WorkflowID"].ToString();
                para["Sequence"] = dr["workflowstepsequence"].ToString();
                para["FactoryID"] = dr["originalfactoryid"].ToString();//用户当前分厂，此处默认为开卡分厂
                m_ContainerShip.FixedContainerShip(para, m_Common);
            }
            //处理当前工艺在子工艺，需要父工序转工的记录
            //faShipContainerDt.Columns.Add("WorkFlowStepID");
            //faShipContainerDt.Columns.Add("WorkflowID");
            //faShipContainerDt.Columns.Add("workflowstepsequence");
            //faShipContainerDt.Columns.Add("originalfactoryid");
            //foreach (DataRow dr in faShipContainerDt.Rows)
            //{
            //    DataRow[] tempDrs = faStepShipDt.Select("Containerid='"+dr["Containerid"]+"'");
            //    Boolean IsContinue = false;
            //    foreach (DataRow temDr in tempDrs)
            //    {
            //        int n = IsExitShipRecord(temDr);
            //        if (IsContinue)
            //            continue;
            //        //已存在转工，但未转入
            //        if (n == 1)
            //            IsContinue = true;
            //        //
            //        if (n == 2) //子工艺的父工序已经转回在5分钟之内
            //            IsContinue = true; 
            //        if (n==0)//不存在转工
            //        { 
            //            IsContinue = true;
            //            dr["WorkFlowStepID"] = temDr["WorkFlowStepID"];
            //            dr["WorkflowID"] = temDr["WorkflowID"];
            //            dr["workflowstepsequence"] = temDr["workflowstepsequence"];
            //            dr["originalfactoryid"] = temDr["originalfactoryid"];
            //        }

            //    }
            //    if (dr.IsNull("WorkFlowStepID"))
            //        continue;
            //    para["ContainerID"] = dr["ContainerID"].ToString();
            //    para["WorkFlowStepID"] = dr["WorkFlowStepID"].ToString();
            //    para["UserInfoFactory"] = dr["originalfactoryid"].ToString();//用户当前分厂，此处默认为开卡分厂
            //    para["WorkflowID"] = dr["WorkflowID"].ToString();
            //    para["Sequence"] = dr["workflowstepsequence"].ToString();
            //    para["FactoryID"] = dr["originalfactoryid"].ToString();//用户当前分厂，此处默认为开卡分厂
            //    m_ContainerShip.FixedContainerShip(para, m_Common);
            //}

        }

        #endregion

        #region 补充移动（处理检验后没移动的记录） add:Wangjh 20180620
        /// <summary>
        /// 查询移动失败的批次
        /// </summary>
        /// <returns></returns>
        DataTable GetNeedMoveContainer()
        {
            string strSql = @"SELECT cci.containerid,cci.workflowstepsequence,cci.workflowstepid,cci.workflowstepname,cci.workflowid,cci.originalfactoryid,cci.qty,cci.containername,e.employeename username,e.password PASSWORD,e.employeeid,
max(csr.checkdate) lastcheckdate,cci.iscommissioning,cl.containercommissioningid,tows.workflowstepname shiptostepname,tows.workflowstepid shiptostepid,tows.sequence shiptostepseq FROM containercurrentinfo cci
LEFT JOIN containersteprecord csr ON csr.containerid=cci.containerid AND csr.workflowstepid=cci.workflowstepid
left join containershiprecord csh on csh.containershiprecordid=cci.shipid and csh.isuse=0
left join containercommidetail cl on cl.containerid=cci.containerid and cl.workflowstepid=cci.workflowstepid and cl.isuse=0
LEFT JOIN employee e ON e.employeeid=csr.checkemployeeid
LEFT JOIN container c ON c.containerid=cci.containerid
LEFT JOIN Currentstatus cu ON cu.currentstatusid=c.currentstatusid
left join workflowstep tows on tows.workflowstepid=csh.toworkflowstepid
WHERE csr.checkdate>=sysdate-{0} and cci.containerstatus=1 AND csr.usecompleted=1 
and (cci.factoryname not like '装配%' or cci.factoryname not like '试车%' or cci.factoryname not like '修理%' )
AND cci.workflowstepid=cu.workflowstepid 
AND (cci.isship=0 or (cci.isship=1 and cci.workflowstepid!=csh.toworkflowstepid)  )
group by cci.containerid,cci.workflowstepsequence,cci.workflowstepid,cci.workflowstepname,
cci.workflowid,cci.originalfactoryid,cci.qty,cci.containername,e.employeename ,e.password ,
e.employeeid,cci.iscommissioning,cl.containercommissioningid,tows.workflowstepname,tows.workflowstepid,tows.sequence";
            strSql = string.Format(strSql, ConfigurationManager.AppSettings["AutoMoveTime"]);
            return DatabaseHelper.Query_ReturnDatTable(strSql);
        }

        /// <summary>
        /// 补充移动（移动失败的）
        /// 如果需要军检，军检反馈结果后，补充移动
        /// </summary>
        public void SupplyMove()
        {
            DataTable dt = GetNeedMoveContainer();
            Dictionary<string, object> para = new Dictionary<string, object>();
            string strMsg = "";
            foreach (DataRow dr in dt.Rows)
            {
                //如果是因为军检而停滞的，不需要补充移动
                string strCheckSql = @"select * from (
select cci.containerid,cci.workflowstepid,cci.containercheckinfoid checkinfoid,cci.isarmycheck,cci.createdate checkdate from containercheckinfo cci
where cci.containerid='{0}' and cci.workflowstepid='{1}' and cci.isuse=0
union all
select cfci.containerid,cfci.workflowstepid,cfci.containerfinishedcheckinfoid checkinfoid,cfci.isarmycheck,cfci.createdate checkdate from containerfinishedcheckinfo cfci
where cfci.containerid='{0}' and cfci.workflowstepid='{1}' and cfci.isuse=0
) order by checkdate desc";
                DataTable checkDt = DatabaseHelper.Query_ReturnDatTable(string.Format(strCheckSql, dr["ContainerID"].ToString(), dr["workflowstepid"].ToString()));
                if (checkDt.Rows.Count == 0)
                    continue;
                if (checkDt.Rows[0]["isarmycheck"].ToString() == "1")//需要军检
                {
                    DataTable armyDt = DatabaseHelper.Query_ReturnDatTable(string.Format(@"select * from ArmyCheckSendToQMS aq 
where aq.containercheckinfoid='{0}' and aq.qms_dealdate is not null", checkDt.Rows[0]["checkinfoid"].ToString()));
                    if (armyDt.Rows.Count == 0) //无军检结果，继续停滞
                    {
                        continue;
                    }
                }
                //外委最后一序不需要移动 add:Wangjh 20221224
                if (dr["iscommissioning"].ToString() == "1")
                {
                    var maxStepId = DatabaseHelper.GetSingle(string.Format(@"select max(cl.workflowstepid) maxstepid from containercommidetail cl
where cl.containercommissioningid='{0}'", dr["containercommissioningid"].ToString()));
                    if (maxStepId != null && maxStepId.ToString() == dr["workflowstepid"].ToString())
                    {
                        continue;
                    }
                }

                para["ContainerID"] = dr["ContainerID"].ToString();
                para["Sequence"] = dr["workflowstepsequence"].ToString();
                para["WorkflowID"] = dr["WorkflowID"].ToString();
                para["OriginalFactoryID"] = dr["OriginalFactoryID"].ToString();
                para["IsShip"] = false;
                para["UserName"] = "18707528";
                para["Password"] = "LYCxxzx8006";
                para["ContainerName"] = dr["ContainerName"].ToString();
                para["EmployeeName"] = dr["username"].ToString();

                Dictionary<string, string> nextpara = new Dictionary<string, string>();
                nextpara["Sequence"] = ((int.Parse(dr["workflowstepsequence"].ToString())) + 1).ToString();
                nextpara["WorkFlowID"] = dr["WorkFlowID"].ToString();
                nextpara["ContainerID"] = dr["ContainerID"].ToString();
                DataTable nextStep = m_Common.GetContainerNoCompleteStep(nextpara);
                ServerHostInfo host = new ServerHostInfo();
                host.UserName = ConfigurationManager.AppSettings["CamstarUserName"].ToString();//"18707528";
                host.Password = ConfigurationManager.AppSettings["CamstarPassword"].ToString();//"LYCxxzx8006";
                string strWorkFlow = "", strWFVersion = "", strToStep = "", strToStepID = "";
                if (nextStep.Rows.Count == 0)//m_Common .IsLastStep(isLastpara )
                {
                    strWorkFlow = "FMW"; strWFVersion = "1"; strToStep = "完工入库";
                }
                else
                {
                    strWorkFlow = nextStep.Rows[0]["WORKFLOWNAME"].ToString(); strWFVersion = nextStep.Rows[0]["WORKFLOWREVISION"].ToString();
                    //如果批次正在转工中，tostep在最大转工序，以最大转工序为准 add:Wangjh 20230412
                    strToStep = nextStep.Rows[0]["workflowstepname"].ToString(); strToStepID = nextStep.Rows[0]["WORKFLOWSTEPID"].ToString();
                    if (!string.IsNullOrWhiteSpace(dr["shiptostepid"].ToString()) && int.Parse(dr["shiptostepseq"].ToString()) < int.Parse(nextStep.Rows[0]["sequence"].ToString()))
                    {
                        strToStep = dr["shiptostepname"].ToString();
                        strToStepID = dr["shiptostepid"].ToString();
                    }
                }

                //检查是否是撤销的 撤销的则不补充移动
                string strSql = string.Format(@" SELECT mv.* FROM Movehistory mv
	                                LEFT JOIN workflowstep ws ON ws.workflowstepid=mv.stepid
	                                LEFT JOIN workflowstep ws2 ON ws2.workflowstepid=mv.tostepid
	                                WHERE mv.changecount=2 and mv.historyid='{0}' AND ws.workflowstepname='{1}' AND ws2.workflowstepname='{2}'  ",
                    dr["ContainerID"].ToString(), dr["workflowstepname"].ToString(), strToStep);
                if (DatabaseHelper.Query_ReturnDatTable(strSql).Rows.Count > 0)
                { continue; }
                strSql = @"select hml.txndate,mv.* from Movehistory mv 
left join historymainline hml on hml.historymainlineid=mv.historymainlineid
where mv.movehistoryid in (select max(mv.movehistoryid) from  Movehistory mv
where mv.historyid='{0}' ) and mv.notes='MoveBack'";
                strSql = string.Format(strSql, dr["ContainerID"].ToString());
                var moveBackDt = DatabaseHelper.Query_ReturnDatTable(strSql);
                if (moveBackDt.Rows.Count > 0)
                {
                    if (DateTime.Parse(moveBackDt.Rows[0]["txndate"].ToString()) > DateTime.Parse(dr["lastcheckdate"].ToString()))//撤销时间大于检验时间
                    {
                        continue;
                    }
                }
                //

                m_Container.ContainerMoveNonStd(host, para["ContainerName"].ToString(), strWorkFlow, strWFVersion, strToStep, para["EmployeeName"].ToString(), strToStepID, ref strMsg);
                if (strWorkFlow == "FMW" && strToStep == "完工入库")
                {
                    m_Container.UpdateContainerBsWorkflow(para["ContainerID"].ToString(), para["WorkflowID"].ToString());
                }
                // m_Common.MoveToNextStepAndFixCommissionOrFixShip(para,ref strMsg);
                LogHelp.WriteLog("补充移动" + para["ContainerName"] + "工序号：" + para["Sequence"] + strMsg);
                //外委
                if (nextStep.Rows.Count > 0 && nextStep.Rows[0]["controlcode"].ToString() == "LY05")
                {
                    Dictionary<string, string> newpara = new Dictionary<string, string>();
                    newpara["WorkflowID"] = para["WorkflowID"].ToString();
                    newpara["Sequence"] = para["Sequence"].ToString();
                    newpara["WorkflowStepID"] = nextStep.Rows[0]["WorkflowStepID"].ToString();
                    newpara["FactoryID"] = dr["OriginalFactoryID"].ToString();
                    newpara["EmployeeID"] = dr["employeeid"].ToString();
                    newpara["OutQty"] = dr["qty"].ToString();
                    newpara["ContainerID"] = dr["ContainerID"].ToString();
                    newpara["ContainerName"] = dr["ContainerName"].ToString();
                    m_Commission.AddFixedCommissionInfo(newpara);
                }
                //
            }

        }
        #endregion

        #region 结转总表批次号 create:Wangjh 20180802
        /// <summary>
        /// 获取批次号
        /// </summary>
        /// <returns></returns>
        DataTable GetContainerNo()
        {
            string strSql = @"select * from ( SELECT SUBSTR(c.togetherflag,INSTR(c.togetherflag,cci.productname)+length(cci.productname||'/')) containerno,c.containerid  FROM container c
                            INNER JOIN containercurrentinfo cci ON cci.containerid=c.containerid
                            WHERE cci.containerno IS NULL AND cci.containertype=7
                            UNION
                            SELECT SUBSTR(c.containername,INSTR(c.containername,cci.productname)+length(cci.productname||'/')) containerno,c.containerid  FROM container c
                            INNER JOIN containercurrentinfo cci ON cci.containerid=c.containerid
                            WHERE cci.containerno IS NULL AND cci.containertype<>7) a
                            WHERE a.containerno IS NOT NULL";
            return DatabaseHelper.Query_ReturnDatTable(strSql);

        }
        /// <summary>
        /// 更新每行的批次号
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        Boolean UpdateContainerNoOfRow(DataRow dr)
        {
            string strSql = string.Format("UPDATE containercurrentinfo cci SET cci.containerno='{0}' WHERE cci.containerid='{1}'",
                                            dr["containerno"].ToString(), dr["containerid"].ToString());
            int i = DatabaseHelper.ExecuteSql(strSql);
            if (i > 0)
                return true;
            else
                return false;
        }
        /// <summary>
        /// 更新批次号
        /// </summary>
        public void UpdateContainerNo()
        {
            DataTable dt = GetContainerNo();
            foreach (DataRow dr in dt.Rows)
            {
                UpdateContainerNoOfRow(dr);
            }
        }
        #endregion

        #region 储存领用人，时间，数量 add:Wangjh 20181015
        /// <summary>
        /// 获取需要储存的数据
        /// </summary>
        /// <returns></returns>
        DataTable GetSendMaterialData()
        {
            string strSql = @"SELECT e.employeeid,mv.qty,hsm.txndate,cci.CONTAINERID FROM CONTAINERCURRENTINFO CCI 
                        LEFT JOIN Userattribute ut ON ut.parentid=cci.containerid AND ut.userattributename='领用人'
                        LEFT JOIN employee e ON e.fullname=ut.attributevalue
                        LEFT JOIN movehistory mv ON mv.historyid=cci.containerid
                        LEFT JOIN workflowstep ws ON ws.workflowstepid=mv.stepid
                        LEFT JOIN historymainline hsm ON hsm.historymainlineid=mv.historymainlineid
                        WHERE cci.sendmaterialworkid IS NULL AND ws.workflowstepname='工人领料' AND e.employeeid IS NOT NULL AND ROWNUM<1001";
            return DatabaseHelper.Query_ReturnDatTable(strSql);
        }
        /// <summary>
        /// 更新每行的发料信息
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        Boolean updateSendMaterialOfRow(DataRow dr)
        {
            string updateSql = "UPDATE containercurrentinfo cci SET cci.sendmaterialworkid=:sendmaterialworkid ,cci.sendmaterialdate=:sendmaterialdate ,cci.sendmaterialqty =:sendmaterialqty WHERE cci.containerid=:containerid";
            OracleParameter[] updatePara = new OracleParameter[4];
            updatePara[0] = DatabaseHelper.NewParameter(":CONTAINERID", dr["CONTAINERID"], OracleType.VarChar);
            updatePara[1] = DatabaseHelper.NewParameter(":sendmaterialworkid", dr["employeeid"], OracleType.VarChar);
            updatePara[2] = DatabaseHelper.NewParameter(":sendmaterialqty", dr["QTY"], OracleType.Number);
            updatePara[3] = DatabaseHelper.NewParameter(":sendmaterialdate", dr["txndate"], OracleType.DateTime);
            int i = DatabaseHelper.ExecuteSql(updateSql, updatePara);
            if (i > 0)
                return true;
            else
                return false;
        }
        /// <summary>
        /// 更新发料信息
        /// </summary>
        public void UpdateSendMaterial()
        {
            DataTable dt = GetSendMaterialData();
            foreach (DataRow dr in dt.Rows)
            {
                updateSendMaterialOfRow(dr);
            }
        }
        #endregion

        #region 1、热表处理连续加工转工序的工控网返回的数据，主卡无法自动往下移动，补充其移动。2、热表子卡干完，主卡未填充报工检验的数据并将其补充。add by zhangrj 20241126

        /// <summary>
        /// 补充主卡移动、以及转工序的报工检验数据（针对热表工控网）
        /// </summary>
        public void UpdateFaContainerMoveByRB()
        {
            /*
             * 1、热表处理连续加工转工序的工控网返回的数据，主制分厂主卡无法自动往下移动，补充其移动
             */
            string rbFactoryID = ConfigurationManager.AppSettings["RBFactoryID"].ToString();//热表ID;
            ServerHostInfo host = new ServerHostInfo();
            host.UserName = ConfigurationManager.AppSettings["CamstarUserName"].ToString();//"18707528";
            host.Password = ConfigurationManager.AppSettings["CamstarPassword"].ToString();//"LYCxxzx8006";
            string sql = string.Format(@"
                        SELECT * FROM (
                        SELECT Distinct cci.containerid,cci.containername,cci.workflowid,cci.workflowname,cci.workflowrevision,csr.containershiprecordid,
                        ws1.workflowstepid nextworkflowstepid,ws1.workflowstepname nextworkflowstepname,ws1.sequence nextsequence,scci.containerid subcontainerid, e.employeename
                        FROM containershiprecord csr 
                        LEFT JOIN containercurrentinfo cci ON cci.containerid = csr.containerid AND cci.shipid = csr.containershiprecordid
                        LEFT JOIN workflowstep ws ON ws.workflowstepid = cci.workflowstepid
                        LEFT JOIN workflowstep ws1 ON ws1.workflowid = ws.workflowid AND ws1.sequence = (ws.sequence + 1)
                        LEFT JOIN containersubcontainer csc ON csc.containerid = cci.containerid AND csc.workflowstepname = ws.workflowstepname
                        LEFT JOIN containercurrentinfo scci ON scci.containerid = csc.subcontainerid 
                        LEFT JOIN employee e ON e.employeeid = csr.toacceptor
                        WHERE csr.toacceptdate IS NOT NULL AND csr.tofactoryid = '{0}' AND csr.isuse = 0 AND cci.containerstatus = 1 AND scci.containerstatus = 1
                        AND csr.workflowstepid != csr.toworkflowstepid 
                        AND NOT EXISTS(SELECT 1 FROM containershiprecive csv WHERE csv.containershiprecordid = csr.containershiprecordid AND csv.isuse = 0)
                        )k
                        WHERE EXISTS (SELECT 1 FROM containershiprecordstep csrs WHERE csrs.containershiprecordid = k.containershiprecordid AND csrs.workflowstepid = k.nextworkflowstepid) --主卡下一序也在同一转工记录里
                        AND EXISTS(SELECT 1 FROM containercheckinfo c WHERE c.containerid = k.subcontainerid AND c.isuse = 0) -- 主卡的当前序的子卡已经完工", rbFactoryID);
            DataTable dtFa = DatabaseHelper.Query_ReturnDatTable(sql);
            string strMsg = string.Empty;
            foreach (DataRow item in dtFa.Rows)
            {
                /*检测是否报废，报废则要更改连续转工的所有子卡*/
                ChangeContinueShipSpecSubCon(item);
                strMsg = "";
                /*主制批次移动到下一序*/
                m_Container.ContainerMoveNonStd(host, item["ContainerName"].ToString(), item["workflowname"].ToString(), item["workflowrevision"].ToString(), item["nextworkflowstepname"].ToString(), item["employeename"].ToString(), item["nextworkflowstepid"].ToString(), ref strMsg);
                LogHelp.WriteLog("（热表对应主卡）补充移动" + item["ContainerName"].ToString() + "工序：" + item["nextworkflowstepname"].ToString() + strMsg);
            }
            /* 
             * 2、补充热表子卡全部干完，主卡转工序还未有生产数据的
             * （热表已经将主卡批次转工完成后才会触发）
             */
            sql = string.Format(@"SELECT * FROM (
                                SELECT Distinct csr.containerid,ws.workflowstepid,ws.workflowstepname,fac.containertype,fac.qty,subc.containerid subcontainerid,subc.containername subcontainername
                                FROM containershiprecord csr 
                                LEFT JOIN containercurrentinfo fac ON fac.containerid = csr.containerid
                                LEFT JOIN containershiprecive csv ON csv.containershiprecordid = csr.containershiprecordid
                                LEFT JOIN containershiprecordstep csrs ON csrs.containershiprecordid = csr.containershiprecordid
                                LEFT JOIN workflowstep ws ON ws.workflowstepid = csrs.workflowstepid
                                LEFT JOIN containersubcontainer csc ON csc.containerid = csr.containerid AND csc.workflowstepname = ws.workflowstepname
                                LEFT JOIN containercurrentinfo subc ON subc.containerid = csc.subcontainerid 
                                WHERE fac.containerstatus = 1 AND csr.isuse = 0 AND csr.tofactoryid = '{0}' AND csv.completedate >= SYSDATE - 30 AND subc.containerstatus = 1 AND subc.isinstore = 1
                                )k
                                WHERE EXISTS(SELECT 1 FROM containercheckinfo cci WHERE cci.containerid = k.subcontainerid AND cci.isuse = 0)
                                      AND NOT EXISTS(SELECT 1 FROM containersteprecord csd 
                                                        WHERE csd.containerid = k.containerid AND csd.workflowstepname = k.workflowstepname AND csd.checkdate IS NOT NULL)
                                      AND NOT EXISTS(SELECT 1 FROM containercommidetail cc WHERE cc.containerid = k.containerid AND cc.workflowstepname = k.workflowstepname AND cc.isuse = 0)
                                      AND NOT EXISTS(SELECT 1 FROM containersplitinfo csi WHERE csi.splitcontainername = k.subcontainername)", rbFactoryID);
            DataTable dtShip = DatabaseHelper.Query_ReturnDatTable(sql);
            foreach (DataRow item in dtShip.Rows)
            {
                FillFaContainerProductData(item, rbFactoryID);
            }
        }
        /// <summary>
        /// 当前子卡存在报废，则要将连续转工下序的子卡更改在制数以及删除其派工和排产信息
        /// </summary>
        /// <param name="dr"></param>
        /// <returns></returns>
        private void ChangeContinueShipSpecSubCon(DataRow dr)
        {
            string sql = string.Format(@"SELECT cci.lossqty,c.qty FROM containercheckinfo cci 
                            LEFT JOIN containercurrentinfo c ON c.containerid = cci.containerid
                            WHERE cci.containerid = '{0}' AND NVL(cci.lossqty, 0) > 0", dr["subcontainerid"].ToString());
            DataTable dtCheck = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dtCheck.Rows.Count > 0) //如果当前子卡存在报废，则要将连续转工后面的工序的子卡更改在制数以及删除其派工和排产信息
            {
                string toAppID_RB = ConfigurationManager.AppSettings["ToAppID_RB"].ToString();//热表推送工控网目标ID;
                sql = string.Format(@"SELECT * FROM (SELECT Distinct c.containerid FROM containershiprecord csr
                        LEFT JOIN containershiprecordstep csrs ON csrs.containershiprecordid = csr.containershiprecordid
                        LEFT JOIN workflowstep ws ON ws.workflowstepid = csrs.workflowstepid
                        LEFT JOIN containersubcontainer csc ON csc.containerid = csr.containerid AND csc.workflowstepname = ws.workflowstepname
                        LEFT JOIN container c ON c.containerid = csc.subcontainerid
                        WHERE csr.containershiprecordid = '{0}' AND c.status != 0 AND ws.sequence >= {1}
                        )sub WHERE NOT EXISTS(SELECT 1 FROM containerstepworkreport2 csw WHERE csw.containerid = sub.containerid AND csw.isuse = 0)", dr["containershiprecordid"].ToString(), dr["nextsequence"].ToString());
                DataTable dtNextAllCon = DatabaseHelper.Query_ReturnDatTable(sql);//获取后续的所有转工序的子卡
                ArrayList sqlList = new ArrayList();
                int changeQty = int.Parse(dtCheck.Rows[0]["lossqty"].ToString());//需要更改的数量（当前子卡的报废数）
                foreach (DataRow item in dtNextAllCon.Rows)
                {
                    sqlList.Clear();
                    /*
                     * 查出要删除的数据，并推送给工控网
                     */
                    /*推送排产明细*/
                    sql = string.Format("SELECT ap.apsplandetailid FROM apsplandetail2 ap WHERE ap.containerid = '{0}'", item["containerid"].ToString());
                    DataTable dtApsDetail = DatabaseHelper.Query_ReturnDatTable(sql);
                    sqlList.AddRange(m_Common.InsertSyncTableChangeRecode(dtApsDetail, "apsplandetail2", "apsplandetailid", toAppID_RB, 3, false));
                    /*推送排产主表*/
                    sql = string.Format("SELECT ai.apsplaninfoid FROM apsplaninfo ai WHERE ai.containerid = '{0}'", item["containerid"].ToString());
                    DataTable dtApsInfo = DatabaseHelper.Query_ReturnDatTable(sql);
                    sqlList.AddRange(m_Common.InsertSyncTableChangeRecode(dtApsInfo, "apsplaninfo", "apsplaninfoid", toAppID_RB, 3, false));
                    /*推送工步派工*/
                    sql = string.Format("SELECT csd.containerstepdispatchid FROM containerstepdispatch2 csd WHERE csd.containerid = '{0}' AND csd.isuse = 0", item["containerid"].ToString());
                    DataTable dtDis2 = DatabaseHelper.Query_ReturnDatTable(sql);
                    sqlList.AddRange(m_Common.InsertSyncTableChangeRecode(dtDis2, "containerstepdispatch2", "containerstepdispatchid", toAppID_RB, 2, false));
                    /*推送工序派工*/
                    sql = string.Format("SELECT csd.containerstepdispatchid FROM containerstepdispatch csd WHERE csd.containerid = '{0}' AND csd.isuse = 0", item["containerid"].ToString());
                    DataTable dtDis = DatabaseHelper.Query_ReturnDatTable(sql);
                    sqlList.AddRange(m_Common.InsertSyncTableChangeRecode(dtDis, "containerstepdispatch", "containerstepdispatchid", toAppID_RB, 2, false));
                    /*
                     * 删除该子卡的排产和派工
                     */
                    sqlList.Add(string.Format("DELETE apsplandetail2 ap WHERE ap.containerid = '{0}'", item["containerid"].ToString()));
                    sqlList.Add(string.Format("DELETE apsplaninfo ai WHERE ai.containerid = '{0}'", item["containerid"].ToString()));
                    sqlList.Add(string.Format("UPDATE containerstepdispatch2 csd SET csd.isuse = 1 WHERE csd.containerid = '{0}' AND csd.isuse = 0", item["containerid"].ToString()));
                    sqlList.Add(string.Format("UPDATE containerstepdispatch csd SET csd.isuse = 1 WHERE csd.containerid = '{0}' AND csd.isuse = 0", item["containerid"].ToString()));
                    DatabaseHelper.ExecuteSqlTran(sqlList);
                    /*更改该子卡数量*/
                    m_Container.ChangeContainerQty(item["containerid"].ToString(), -changeQty);
                }
            }
        }
        /// <summary>
        /// 补充主制分厂父卡的生产数据（热表）
        /// </summary>
        /// <param name="subContainerID"></param>
        private void FillFaContainerProductData(DataRow dr, string rbFactoryID)
        {
            ArrayList sqlList = new ArrayList();
            /*查询子卡的检验信息*/
            string sql = string.Format(@"SELECT NVL(csr.checkqty,0) checkqty,NVL(csr.acceptanceqty,0) passqty,nvl(csr.lossqty,0) lossqty,nvl(csr.acceptanceqty2,0) acceptanceqty2,
                                    nvl(csr.defectqty,0) defectqty,nvl(csr.reworkqty,0) reworkqty,to_char(csr.createdate,'yyyy-MM-dd hh24:mi:ss') checkdate,csr.checkerid,e.fullname checkempname
                                    FROM containercheckinfo csr
                                    LEFT JOIN employee e ON e.employeeid = csr.checkerid
                                    WHERE csr.containerid = '{0}' AND csr.isuse = 0", dr["subcontainerid"].ToString());
            DataTable dtSubCheck = DatabaseHelper.Query_ReturnDatTable(sql);
            /*查询子卡的所有分卡的检验信息*/
            sql = string.Format(@"SELECT NVL(csr.checkqty,0) checkqty,NVL(csr.acceptanceqty,0) passqty,nvl(csr.lossqty,0) lossqty,nvl(csr.acceptanceqty2,0) acceptanceqty2,
                                    nvl(csr.defectqty,0) defectqty,nvl(csr.reworkqty,0) reworkqty
                                    FROM containersplitinfo csi
                                    LEFT JOIN containercurrentinfo c ON c.containername = csi.splitcontainername
                                    LEFT JOIN containercheckinfo csr ON csr.containerid = c.containerid
                                    WHERE csi.containerid = '{0}' AND c.containerstatus != 0 AND csr.isuse = 0", dr["subcontainerid"].ToString());
            DataTable dtSubSplitCheck = DatabaseHelper.Query_ReturnDatTable(sql);
            /*查询子卡的报工信息*/
            sql = string.Format(@"SELECT csw.qty,to_char(csw.createdate,'yyyy-MM-dd hh24:mi:ss') reportdate,csw.workerid
                                FROM containerstepworkreport csw 
                                WHERE csw.containerid = '{0}' AND csw.isuse = 0", dr["subcontainerid"].ToString());
            DataTable dtSubWorkReport = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dtSubCheck.Rows.Count == 0 || dtSubWorkReport.Rows.Count == 0)
            {
                return;
            }
            int passqty = int.Parse(dtSubCheck.Rows[0]["passqty"].ToString()); //合格数
            int lossqty = int.Parse(dtSubCheck.Rows[0]["lossqty"].ToString()); //报废数
            int defectqty = int.Parse(dtSubCheck.Rows[0]["defectqty"].ToString()); //超差数
            int reworkqty = int.Parse(dtSubCheck.Rows[0]["reworkqty"].ToString()); //返修数
            if (dtSubSplitCheck.Rows.Count > 0) //如果子卡存在分卡，则要累加分卡的检验数
            {
                passqty += dtSubSplitCheck.AsEnumerable().Sum(p => int.Parse(p["passqty"].ToString()));
                lossqty += dtSubSplitCheck.AsEnumerable().Sum(p => int.Parse(p["lossqty"].ToString()));
                defectqty += dtSubSplitCheck.AsEnumerable().Sum(p => int.Parse(p["defectqty"].ToString()));
                reworkqty += dtSubSplitCheck.AsEnumerable().Sum(p => int.Parse(p["reworkqty"].ToString()));
            }
            /*
             * 检查报工记录表
             */
            sql = string.Format("SELECT csw.containerstepworkreportid FROM containerstepworkreport csw WHERE csw.containerid = '{0}' AND csw.workflowstepid = '{1}' AND csw.isuse = 0", dr["containerid"].ToString(), dr["workflowstepid"].ToString());
            DataTable dtWorkReport = DatabaseHelper.Query_ReturnDatTable(sql); //获取工序报工
            string containerStepWorkReportID = string.Empty; //报工ID
            if (dtWorkReport.Rows.Count == 0)
            {
                //插入工序报工（自动报工）
                containerStepWorkReportID = Guid.NewGuid().ToString();
                sql = string.Format(@"INSERT INTO containerstepworkreport(checktype,containerid,containerstepdispatchid,containerstepworkreportid,createdate,factoryid,isuse,qty,workerid,workflowstepid,lossqty)
                                                VALUES('30','{0}','{1}','{2}',to_date('{3}','yyyy-MM-dd hh24:mi:ss'),'{4}',0,{5},'{6}','{7}',{8})",
                                    dr["containerid"].ToString(), "", containerStepWorkReportID, dtSubWorkReport.Rows[0]["reportdate"].ToString(), rbFactoryID, passqty + lossqty, dtSubWorkReport.Rows[0]["workerid"].ToString(), dr["workflowstepid"].ToString(), lossqty);
                sqlList.Add(sql);
            }
            else
            {
                containerStepWorkReportID = dtWorkReport.Rows[0]["containerstepworkreportid"].ToString();
            }
            /*
             * 检查检验记录表
             */
            string containerCheckInfoID = string.Empty; //检验ID
            sql = string.Format("SELECT cci.containercheckinfoid FROM containercheckinfo cci WHERE cci.containerid = '{0}' AND cci.workflowstepid = '{1}' AND cci.isuse = 0", dr["containerid"].ToString(), dr["workflowstepid"].ToString());
            DataTable dtCheck = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dtCheck.Rows.Count == 0)
            {
                containerCheckInfoID = Guid.NewGuid().ToString();
                //插入工序检验
                sql = string.Format(@"INSERT INTO containercheckinfo(acceptanceqty,checkerid,checkqty,containercheckinfoid,containerid,createdate,defectqty,factoryid,isuse,lossqty,reworkqty,workflowstepid,containerstepworkreportid,acceptanceqty2)
                                            VALUES({0},'{1}',{2},'{3}','{4}',to_date('{5}','yyyy-MM-dd hh24:mi:ss'),{6},'{7}',0,{8},{9},'{10}','{11}',{12})",
                                    passqty, dtSubCheck.Rows[0]["checkerid"].ToString(), passqty + lossqty, containerCheckInfoID, dr["containerid"].ToString(), dtSubCheck.Rows[0]["checkdate"].ToString(), defectqty,
                                    rbFactoryID, lossqty, reworkqty, dr["workflowstepid"].ToString(), containerStepWorkReportID, passqty - defectqty - reworkqty);
                sqlList.Add(sql);
            }
            else
            {
                containerCheckInfoID = dtCheck.Rows[0]["containercheckinfoid"].ToString();
            }
            /*
             * 检查生产记录表
             */
            sql = string.Format(@"SELECT 1 FROM containersteprecord csr WHERE csr.containerid = '{0}' AND csr.workflowstepid = '{1}'", dr["containerid"].ToString(), dr["workflowstepid"].ToString());
            if (DatabaseHelper.GetSingle(sql) != null)
            {
                sql = string.Format(@"UPDATE containersteprecord csr SET csr.checkdate = to_date('{0}','yyyy-MM-dd hh24:mi:ss'), csr.checkemployeeid = '{1}', 
                                csr.checkemployeename = '{2}',csr.passqty = {3},csr.lossqty = {4},csr.usecompleted = 1 WHERE csr.containerid = '{5}' AND csr.workflowstepid = '{6}'",
                                   dtSubCheck.Rows[0]["checkdate"].ToString(), dtSubCheck.Rows[0]["checkerid"].ToString(), dtSubCheck.Rows[0]["checkempname"].ToString(), passqty, lossqty, dr["containerid"].ToString(), dr["workflowstepid"].ToString());
                sqlList.Add(sql);
            }
            DatabaseHelper.ExecuteSqlTran(sqlList);
            /*
             * 如果存在报废，则更新在制数
             */
            if (lossqty > 0)
            {
                if (dr["containertype"].ToString() == "3") //如果主卡是批量带子序号，则要报废子序号
                {
                    /*查询出热表子卡的报废子序号以及子卡的分卡报废子序号*/
                    sql = string.Format(@"SELECT c.containerid,c.containername,c.qualificationnum FROM Checkqtychangerecord cq
                                        LEFT JOIN container c ON c.containerid = cq.containerid
                                        WHERE c.parentcontainerid = '{0}'
                                        UNION ALL
                                        SELECT cc.containerid,cc.containername,cc.qualificationnum  FROM containersplitinfo csi
                                        LEFT JOIN container c ON c.containername = csi.splitcontainername
                                        LEFT JOIN container cc ON cc.parentcontainerid = c.containerid
                                        INNER JOIN Checkqtychangerecord cq ON cq.containerid = cc.containerid
                                        WHERE csi.containerid = '{0}' AND c.status != 0", dr["subcontainerid"].ToString());
                    DataTable dtSubLoss = DatabaseHelper.Query_ReturnDatTable(sql);
                    /*查询出父卡的子序号*/
                    sql = string.Format(@"SELECT c.containerid,c.qualificationnum FROM container c WHERE c.parentcontainerid = '{0}'", dr["containerid"].ToString());
                    DataTable dtFaChild = DatabaseHelper.Query_ReturnDatTable(sql);
                    foreach (DataRow item in dtSubLoss.Rows)
                    {
                        DataRow[] faChild = dtFaChild.Select("qualificationnum='" + item["qualificationnum"].ToString() + "'"); //找出报废子卡序号对应的主卡序号
                        if (faChild.Length > 0)
                        {
                            /*添加子序号批次报废记录*/
                            Dictionary<string, string> para = new Dictionary<string, string>();
                            para.Add("containerCheckInfoID", containerCheckInfoID);//检验ID
                            para.Add("containerID", faChild[0]["containerid"].ToString());//子序号批次ID
                            para.Add("changeQtyType", "2");//数量变更类型（2为报废）
                            para.Add("qty", (-1).ToString());//变更数量
                            para.Add("reasonID", "");
                            para.Add("scrapSourceType", "4");//数据来源类型(4为转工)
                            para.Add("containerStepWorkReportID", containerStepWorkReportID);//报工ID
                            para.Add("EmployeeID", dtSubCheck.Rows[0]["checkerid"].ToString());//记录人（取检验人）
                            para.Add("WorkflowstepID", dr["workflowstepid"].ToString());//工序ID
                            m_Container.AddCheckQtyChangeRecord(para);
                            /*更改子序号批次数量*/
                            m_Container.ChangeContainerQty(faChild[0]["containerid"].ToString(), -1);
                        }
                    }
                }
                else
                {
                    /*添加主卡批次报废记录*/
                    Dictionary<string, string> para = new Dictionary<string, string>();
                    para.Add("containerCheckInfoID", containerCheckInfoID);//检验ID
                    para.Add("containerID", dr["containerid"].ToString());//批次ID
                    para.Add("changeQtyType", "2");//数量变更类型（2为报废）
                    para.Add("qty", (-lossqty).ToString());//变更数量
                    para.Add("reasonID", "");
                    para.Add("scrapSourceType", "4");//数据来源类型(4为转工)
                    para.Add("containerStepWorkReportID", containerStepWorkReportID);//报工ID
                    para.Add("EmployeeID", dtSubCheck.Rows[0]["checkerid"].ToString());//记录人（取检验人）
                    para.Add("WorkflowstepID", dr["workflowstepid"].ToString());//工序ID
                    m_Container.AddCheckQtyChangeRecord(para);
                }
                /*更改主卡批次数量*/
                m_Container.ChangeContainerQty(dr["containerid"].ToString(), -lossqty);
            }
        }
        #endregion

        #region 自动创建工装工具批次 add by zhangrj 20250108
        /// <summary> 
        /// 自动创建工装工具批次 add by zhangrj 20250108
        /// </summary>
        public void CreateGZContainerInfo()
        {
            string gzFactoryID = ConfigurationManager.AppSettings["GZFactoryID"].ToString();//工装工具分厂ID
            string sql = string.Format(@"SELECT e.employeeid,e.employeename,f.factoryname,f.factoryid FROM factory f
                                        LEFT JOIN userattribute u ON u.parentid = f.factoryid
                                        INNER JOIN employee e ON e.employeename = u.attributevalue
                                        WHERE f.factoryid = '{0}' AND u.userattributename = '开卡人'", gzFactoryID);
            DataTable dtEmp = DatabaseHelper.Query_ReturnDatTable(sql);//获取开卡人
            if (dtEmp.Rows.Count == 0)
            {
                LogHelp.WriteLog("（工装工具自动开卡）未分配开卡人或开卡人维护有误");
                return;
            }
            DataRow drEmp = dtEmp.Rows[0];
            sql = string.Format(@"SELECT * FROM (SELECT wb.workflowname,MAX(w.workflowid) workflowid,pb.productname,w.taskno  FROM workflow w 
                            LEFT JOIN workflowbase wb ON wb.workflowbaseid = w.workflowbaseid
                            LEFT JOIN product p ON p.productid = w.productid
                            LEFT JOIN productbase pb ON pb.productbaseid = p.productbaseid
                            LEFT JOIN container c ON c.containername = pb.productname || '/' || w.taskno
                            WHERE wb.workflowname != 'FMW' AND wb.workflowname != 'MW' AND w.factoryid = '{0}' AND w.taskno IS NOT NULL AND w.qty IS NOT NULL AND w.workcenterid IS NOT NULL
                            AND NOT EXISTS(
                               SELECT 1 FROM AUTOSTARTCONTAINERERRORINFO a WHERE a.mfgordername = wb.workflowname
                            )
                            AND c.containerid IS NULL
                            GROUP BY wb.workflowname,pb.productname,w.taskno
                            ) WHERE ROWNUM <= 10", gzFactoryID);//获取工装工具可以创建批次的工艺，每次获取10条
            DataTable dtWorkflow = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dtWorkflow.Rows.Count == 0)
            {
                //LogHelp.WriteLog("（工装工具自动开卡）未查询到数据");
                return;
            }
            foreach (DataRow item in dtWorkflow.Rows)
            {
                CreateGZContainerInfo(item["workflowid"].ToString(), drEmp);
            }
        }

        /// <summary>
        /// 创建单个工装工具批次
        /// </summary>
        /// <param name="workflowID">工艺ID</param>
        /// <param name="gzFactoryID">工装工具分厂ID</param>
        private void CreateGZContainerInfo(string workflowID, DataRow drEmp)
        {
            DataTable dtWorkflow = GetGZWorkflowInfo(workflowID);
            if (dtWorkflow.Rows.Count == 0)
            {
                //LogHelp.WriteLog(string.Format("（工装工具自动开卡）工艺：{0}未查询到数据", workflowID));
                return;
            }
            DataRow drWf = dtWorkflow.Rows[0];
            string containerName = string.Format("{0}/{1}", drWf["productName"].ToString(), drWf["taskno"].ToString());//批次号
            if (DatabaseHelper.GetSingle(string.Format("SELECT 1 FROM container c WHERE c.containername = '{0}'", containerName)) != null)
            {
                return;//开过卡，则跳过，不记录
            }
            if (string.IsNullOrWhiteSpace(drWf["productName"].ToString()))
            {
                LogHelp.WriteLog(string.Format("（工装工具自动开卡）工艺：{0}未查询到关联的件号", drWf["workflowname"].ToString()));
                //插入开卡报错记录表，（说明：由于工装工具情况特殊，开卡没有订单号，所以将记录表里的订单ID和订单号存为工艺ID和工艺名，其他不变。）
                m_Auto.CreateAutoStartErrorInfo(new Dictionary<string, string>() { { "MfgOrderID", workflowID },{ "MfgOrderName", drWf["workflowname"].ToString() },
                        { "ProductName", drWf["productName"].ToString() },{ "CreateEmpID", drEmp["employeeid"].ToString() },{ "Notes",  string.Format("（工装工具自动开卡）工艺：{0}未查询到关联的件号", drWf["workflowname"].ToString()) },
                        { "FactoryID", drEmp["factoryid"].ToString() }
                });
                return;
            }
            //填充批次信息
            ContainerStartInfo containerBaseInfo = new ContainerStartInfo();
            containerBaseInfo.ContainerName = containerName;
            containerBaseInfo.YpContainerNo = "";
            containerBaseInfo.YpHeatNo = "";
            containerBaseInfo.YpContainerCardNo = "";
            containerBaseInfo.Qty = drWf["qty"].ToString();
            containerBaseInfo.MfgOrder = "";
            containerBaseInfo.MonthPlan = "";//月度计划
            containerBaseInfo.IsSelfMfg = "1";//默认为是
            FillContainerDefaultInfo(ref containerBaseInfo, drEmp["factoryid"].ToString());
            containerBaseInfo.TogetherFlag = containerName;
            containerBaseInfo.Factory = drEmp["factoryname"].ToString();//分厂名
            containerBaseInfo.CheckTechnique = "";
            containerBaseInfo.UOM = "件";//默认单位为件
            containerBaseInfo.WorkCenter = drWf["workcentername"].ToString();//工区
            containerBaseInfo.Team = drWf["teamname"].ToString();//班组
            containerBaseInfo.StartEmployee = drEmp["employeename"].ToString();//开卡人
            containerBaseInfo.BeginStep = drWf["workflowstepname"].ToString();//开始工序
            containerBaseInfo.ProductName = drWf["productName"].ToString();//件号
            containerBaseInfo.ProductRevision = drWf["productrevision"].ToString();//件号版本
            containerBaseInfo.ProductuseROR = false;
            containerBaseInfo.MfgWorkflowName = drWf["workflowname"].ToString();
            containerBaseInfo.MfgWorkflowRevision = drWf["workflowrevision"].ToString();
            containerBaseInfo.MfgWorkflowuseROR = false;
            containerBaseInfo.WorkflowName = drWf["workflowname"].ToString();//覆盖在制工艺为当前工艺
            containerBaseInfo.WorkflowRevision = drWf["workflowrevision"].ToString();//
            containerBaseInfo.WorkflowuseROR = false;//
            containerBaseInfo.Comment = "";
            containerBaseInfo.PlannedStartDate = "";
            containerBaseInfo.PlannedCompletionDate = "";
            containerBaseInfo.ContainerType = "2";
            containerBaseInfo.MilitaryType = "";
            containerBaseInfo.YpContainerType = "";
            containerBaseInfo.PlannedQty2 = drWf["bjqty"].ToString();//备件数
            ServerHostInfo serverInfo = new ServerHostInfo();
            serverInfo.UserName = ConfigurationManager.AppSettings["CamstarUserName"].ToString();
            serverInfo.Password = ConfigurationManager.AppSettings["CamstarPassword"].ToString();
            containerBaseInfo.ServerHostInfo = serverInfo;
            containerBaseInfo.QualificationQty = "1";
            containerBaseInfo.MfgBatch = "";//机型
            //containerBaseInfo.ProductFamilyList = "";
            /*扩展属性*/
            containerBaseInfo.AttributeList = AddContainerAttribute(containerBaseInfo);
            /*开卡*/
            Camstar.WebClient.WebServicesProxy.InSiteWebServices.ResultStatus result = m_Container.StartContainer(containerBaseInfo);
            if (result.IsError)
            {
                //插入开卡报错记录表，（说明：由于工装工具情况特殊，开卡没有订单号，所以将记录表里的订单ID和订单号存为工艺ID和工艺名，其他不变。）
                m_Auto.CreateAutoStartErrorInfo(new Dictionary<string, string>() { { "MfgOrderID", workflowID },{ "MfgOrderName", drWf["workflowname"].ToString() },
                        { "ProductName", drWf["productName"].ToString() },{ "CreateEmpID", drEmp["employeeid"].ToString() },{ "Notes",  result.Message },
                        { "FactoryID", drEmp["factoryid"].ToString() }
                });
            }
            else
            {
                //删除开卡报错记录
                m_Auto.DeleAutoStartErrorInfoByName(drWf["workflowname"].ToString());
            }
            /*保存批次工序相关数据（如：虚拟序添加到不加工）*/
            SaveGZConStepSomeInfo(containerName, workflowID, drEmp["employeeid"].ToString());
            LogHelp.WriteLog(string.Format("（工装工具自动开卡）批次：{0}{1}", containerBaseInfo.ContainerName, result.IsError ? string.Format("开卡失败，原因：{0}", result.Message) : "开卡成功"));
        }

        /// <summary>
        /// 工装保存批次工序相关的业务数据,用于工装自动开卡后 
        /// </summary>
        /// <param name="containerName"></param>
        /// <param name="workflowID"></param>
        /// <param name="employeeID"></param>
        private void SaveGZConStepSomeInfo(string containerName, string workflowID, string employeeID)
        {
            string sql = string.Format("select containerid from container where containername = '{0}'", containerName);
            DataTable dtCon = DatabaseHelper.Query_ReturnDatTable(sql);
            if (dtCon.Rows.Count == 0)
            {
                return;
            }
            string containerID = dtCon.Rows[0]["containerid"].ToString();
            sql = string.Format(@"SELECT ws.workflowstepid,ws.workflowstepname FROM workflowstep ws 
                                  WHERE ws.workflowid = '{0}'", workflowID);
            DataTable dtStep = DatabaseHelper.Query_ReturnDatTable(sql);
            ArrayList sqlList = new ArrayList();
            foreach (DataRow row in dtStep.Rows)
            {
                if (row["workflowstepname"].ToString().Contains("虚拟序")) //如果是虚拟序，添加到不加工
                {
                    sqlList.Add(String.Format("delete containerstepnoship css where css.CONTAINERID='{0}' and css.WORKFLOWSTEPID='{1}' and css.isuse=0 and css.noship = 2", containerID, row["workflowstepid"].ToString()));
                    sqlList.Add(String.Format(@"INSERT INTO containerstepnoship (CONTAINERSTEPNOSHIPID,CONTAINERID,WORKFLOWSTEPID,ISUSE,NOSHIP,EMPLOYEEID,CREATEDATE) VALUES(sys_guid(),'{0}','{1}',0,2,'{2}',sysdate)", containerID, row["workflowstepid"].ToString(), employeeID));
                }
            }
            DatabaseHelper.ExecuteSqlTran(sqlList);
        }

        /// <summary>
        /// 获取工艺相关信息
        /// </summary>
        /// <param name="workflowID"></param>
        /// <returns></returns>
        private DataTable GetGZWorkflowInfo(string workflowID)
        {
            string sql = string.Format(@"SELECT p.productid,p.productrevision,pb.productname,w.workflowid,wb.workflowname,w.workflowrevision,w.bjqty,w.qty,w.taskno,
                            wc.workcenterid,wc.workcentername,t.teamid,t.teamname,ws.workflowstepname
                            FROM workflow w
                            LEFT JOIN workflowbase wb ON wb.workflowbaseid = w.workflowbaseid
                            LEFT JOIN workcenter wc ON wc.workcenterid = w.workcenterid
                            LEFT JOIN team t ON t.teamid = w.teamid
                            LEFT JOIN workflowstep ws ON ws.workflowid = w.workflowid AND ws.sequence = 1
                            LEFT JOIN product p ON p.productid = w.productid
                            LEFT JOIN productbase pb ON pb.productbaseid = p.productbaseid
                            WHERE w.workflowid = '{0}'", workflowID);
            return DatabaseHelper.Query_ReturnDatTable(sql);
        }

        /// <summary>
        /// 填充批次默认信息
        /// </summary>
        /// <param name="containerBaseInfo"></param>
        /// <param name="factoryId"></param>
        private void FillContainerDefaultInfo(ref ContainerStartInfo containerBaseInfo, string gzFactoryID)
        {
            DataTable levelAttributes = m_Common.GetFatoryAttributes(gzFactoryID);
            DataRow[] datarows = levelAttributes.Select("USERATTRIBUTENAME='默认所有者'");
            string strOwner = "";
            if (datarows.Length > 0)
            {
                strOwner = datarows[0]["ATTRIBUTEVALUE"].ToString();
            }
            datarows = levelAttributes.Select("USERATTRIBUTENAME='默认层级'");
            string strLevel = "";
            if (datarows.Length > 0)
            {
                strLevel = datarows[0]["ATTRIBUTEVALUE"].ToString();
            }
            string strStart = "";
            if (string.IsNullOrWhiteSpace(containerBaseInfo.MfgOrder.ToString()))
            {
                datarows = levelAttributes.Select("USERATTRIBUTENAME='无订单开始原因'");
            }
            else
            {
                datarows = levelAttributes.Select("USERATTRIBUTENAME='订单开始原因'");
            }
            if (datarows.Length > 0)
            {
                strStart = datarows[0]["ATTRIBUTEVALUE"].ToString();
            }

            containerBaseInfo.StartReason = strStart;
            containerBaseInfo.Level = strLevel;
            containerBaseInfo.Owner = strOwner;
            //string test = containerBaseInfo.IsSelfMfg.ToString();
            //if (containerBaseInfo.IsSelfMfg.ToString() == "True")
            //{
            //    datarows = levelAttributes.Select("USERATTRIBUTENAME='自投料流程'");
            //}
            //else
            //{
            //    datarows = levelAttributes.Select("USERATTRIBUTENAME='领料流程'");
            //}
            //if (datarows.Length > 0)
            //{
            //    string[] strWorkflows = datarows[0]["ATTRIBUTEVALUE"].ToString().Split('：');
            //    containerBaseInfo.WorkflowName = strWorkflows.First();
            //    containerBaseInfo.WorkflowRevision = strWorkflows.Last();
            //    containerBaseInfo.WorkflowuseROR = false;
            //}
        }
        /// <summary>
        /// 添加流水卡扩展属性
        /// </summary>
        /// <param name="containerInfo"></param>
        /// <returns></returns>
        private DataTable AddContainerAttribute(ContainerStartInfo containerInfo)
        {
            DataTable attributeDt = new DataTable();
            attributeDt.Columns.Add("ContainerName");
            attributeDt.Columns.Add("Level");
            attributeDt.Columns.Add("Name");
            attributeDt.Columns.Add("Value");
            DataRow row = attributeDt.NewRow();
            SetAttributeRow(ref row, containerInfo, "CheckTechnique", "");
            attributeDt.Rows.Add(row);
            //if (!string.IsNullOrWhiteSpace(containerInfo.MonthPlan.ToString()))
            //{
            //    row = attributeDt.NewRow();
            //    SetAttributeRow(ref row, containerInfo, "monthPlanName", containerInfo.MonthPlan.ToString());
            //}
            row = attributeDt.NewRow();
            SetAttributeRow(ref row, containerInfo, "BeginStep", containerInfo.BeginStep.ToString());
            attributeDt.Rows.Add(row);
            return attributeDt;
        }
        /// <summary>
        /// 设置属性行
        /// </summary>
        /// <param name="row"></param>
        /// <param name="containerInfo"></param>
        /// <param name="attributeName"></param>
        /// <param name="attributeValue"></param>
        private void SetAttributeRow(ref DataRow row, ContainerStartInfo containerInfo, string attributeName, string attributeValue)
        {
            row["ContainerName"] = containerInfo.ContainerName;
            row["Level"] = containerInfo.Level;
            row["Name"] = attributeName;
            row["Value"] = attributeValue;
        }
        #endregion

        #region 删除超过转工计划时间的热表批次 add by zhangrj 20250609
        /// <summary>
        /// 删除超过转工计划时间的热表批次 add by zhangrj 20250609
        /// </summary>
        public void DeleRBContainerForShipOverTime()
        {
            string rbFactoryID = ConfigurationManager.AppSettings["RBFactoryID"].ToString();//热表ID;
            string querySql = @"SELECT ci.customobjectitemsname itemname,ci.customobjectitemsdesc itemdesc FROM CustomObject C
                                LEFT JOIN customobjectitems ci ON ci.customobjectid = c.customobjectid AND ci.isuse = 0
                                WHERE c.customobjectname = '热表删除转工计划' AND c.isuse = 0 AND ci.customobjectitemsname = '删除天数'";
            DataTable dtItem = DatabaseHelper.Query_ReturnDatTable(querySql);//获取删除天数（如果之后有其他配置项，直接去掉删除天数，全部查询出来）
            if (dtItem.Rows.Count == 0)
            {
                return;//不存在该配置项，则不执行
            }
            int deleDays = 0;//删除天数
            if (!int.TryParse(dtItem.Rows[0]["itemdesc"].ToString(), out deleDays))
            {
                return;//如果天数维护有误，则不执行
            }
            /*
             * 查询出热表删除天数前的开卡批次，没有下发派工的，并且主卡转工排产已接收或已撤销了的数据。
             */
            querySql = string.Format(@"SELECT c.containerid,c.containername,c.productid,c.productname,c.qty,wm_concat(ap.apsplandetailid) apsplandetailid
                                        FROM containercurrentinfo c
                                        LEFT JOIN container cc on cc.containerid = c.containerid
                                        INNER JOIN containersubcontainer csc ON csc.subcontainerid = c.containerid
                                        LEFT JOIN containercurrentinfo fac ON fac.containerid = csc.containerid
                                        LEFT JOIN apsplandetail ap ON ap.containerid = fac.containerid AND ap.workflowstepname = csc.workflowstepname  
                                        WHERE cc.status != 0 AND c.originalstartdate <= to_date('{0} 23:59:59', 'yyyy-mm-dd hh24:mi:ss') AND c.originalfactoryid = '{1}' AND ap.specfactoryid = '{1}' AND ap.status IN ('3','4')
                                        AND NOT EXISTS(SELECT 1 FROM containerstepdispatch2 csd WHERE csd.containerid = c.containerid AND csd.isuse = 0) --不存在工步派工
                                        AND NOT EXISTS(SELECT 1 FROM containerstepworkreport csw WHERE csw.containerid = c.containerid AND csw.isuse = 0) --不存在工序报工
                                        AND NOT EXISTS(SELECT 1 FROM containercheckinfo cci WHERE cci.containerid = c.containerid AND cci.isuse = 0) --不存在工序检验
                                        GROUP BY c.containerid,c.containername,c.productid,c.productname,c.qty",
                        DateTime.Now.AddDays(-deleDays).ToShortDateString(), rbFactoryID);
            DataTable dtContainer = DatabaseHelper.Query_ReturnDatTable(querySql);
            ArrayList sqlList = new ArrayList();
            foreach (DataRow item in dtContainer.Rows)
            {
                sqlList.Clear();
                /* 删除该批次的排产*/
                sqlList.Add(string.Format("DELETE apsplandetail2 ap WHERE ap.containerid = '{0}'", item["containerid"].ToString()));
                sqlList.Add(string.Format("DELETE apsplaninfo ai WHERE ai.containerid = '{0}'", item["containerid"].ToString()));
                /* 退回主制批转工序的转工排产（可能有一个子卡对应多个主卡的情况）*/
                sqlList.Add(string.Format("UPDATE apsplandetail apd SET apd.shipreceiveempid = null, apd.shipreceivedate = null, apd.status = '4', apd.lastchangedate = to_date('{0}','yyyy/mm/dd hh24:mi:ss') WHERE apd.apsplandetailid IN ('{1}')", DateTime.Now.ToString(), item["apsplandetailid"].ToString().Replace(",", "','")));
                DatabaseHelper.ExecuteSqlTran(sqlList);
                /* 删除该批次*/
                if (m_Container.UpdateDelContainer(string.Format("'{0}'", item["containername"].ToString())))
                {
                    /* 添加删除批次记录*/
                    Dictionary<string, string> paraDic = new Dictionary<string, string>();
                    paraDic["containerid"] = item["containerid"].ToString();
                    paraDic["containername"] = item["containername"].ToString();
                    paraDic["productid"] = item["productid"].ToString();
                    paraDic["productname"] = item["productname"].ToString();
                    paraDic["qty"] = item["qty"].ToString();
                    paraDic["operatorid"] = "";
                    paraDic["operreason"] = "转工超期删除（服务自动）";
                    paraDic["opertype"] = "1";
                    m_Container.AddDeleteContainerRecord(paraDic);
                }
            }
            /*处理已删除后但是批次状态未变更的数据（偶发）*/
            querySql = string.Format(@"UPDATE container c SET c.status = 0 WHERE c.containerid IN (
                        SELECT c.containerid FROM container c WHERE c.originalfactoryid = '{0}' AND c.status = 1 AND c.containerid = c.containername
                        AND NOT EXISTS(SELECT 1 FROM containercurrentinfo cci WHERE cci.containerid = c.containerid))", rbFactoryID);
            DatabaseHelper.ExecuteSql(querySql);
        }
        #endregion

        #region 更新工艺变更暂停分批出的批次暂停信息 add by zhangrj 20250903
        /// <summary>
        /// 更新工艺变更暂停分批出的批次暂停信息 add by zhangrj 20250903
        /// </summary>
        public void SaveWfChangeSplitHoldInfo()
        {
            string sql = string.Format(@"SELECT DISTINCT c.containerid,c.containername,c.productid,c.productname,c.qty 
                    FROM containercurrentinfo c
                    LEFT JOIN containersplitinfo s ON s.splitcontainername = c.containername  
                    WHERE s.splitreason = '工艺变更解冻分批' AND NVL(c.ishold, 0) = 0
                    AND NOT EXISTS(SELECT 1 FROM opercontainerrecord o WHERE o.containerid = c.containerid 
                                    AND o.opertype = '2' AND o.operreason = '工艺变更暂停')");
            DataTable dtCon = DatabaseHelper.Query_ReturnDatTable(sql);
            ArrayList sqlList = new ArrayList();
            StringBuilder sqlBl = new StringBuilder();
            foreach (DataRow dr in dtCon.Rows)
            {
                sqlBl.Clear();
                sqlList.Clear();
                //插入批次暂停记录
                sqlBl.Append(@"INSERT INTO OperContainerRecord(containerid,containername,productid,productname,operatorid,operreason,qty,createdate,opertype)
                VALUES(");
                sqlBl.AppendFormat("'{0}',", dtCon.Rows[0]["containerid"].ToString());
                sqlBl.AppendFormat("'{0}',", dtCon.Rows[0]["containername"].ToString());
                sqlBl.AppendFormat("'{0}',", dtCon.Rows[0]["productid"].ToString());
                sqlBl.AppendFormat("'{0}',", dtCon.Rows[0]["productname"].ToString());
                sqlBl.AppendFormat("'{0}',", Guid.NewGuid().ToString());
                sqlBl.AppendFormat("'{0}',", "工艺变更暂停");
                sqlBl.AppendFormat("{0},", dtCon.Rows[0]["qty"].ToString());
                sqlBl.Append("SYSDATE, '2')");
                if (sqlList.Contains(sqlBl.ToString()))
                {
                    continue;
                }
                sqlList.Add(sqlBl.ToString());
                sqlBl.Clear();
                //更新批次暂停
                sqlBl.AppendFormat("UPDATE containercurrentinfo c SET c.ishold = 1 WHERE c.containername = '{0}'", dr["containername"].ToString());
                sqlList.Add(sqlBl.ToString());
                DatabaseHelper.ExecuteSqlTran(sqlList);
            }
        }
        #endregion

        #endregion

    }
}
